/****************************************************************************** * This program converts a Base64 back into the original binary file. * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ #undef NDEBUG #include "Utils.hpp" #include #include #include #include #include using namespace Utils; using namespace std; static string BASE64_CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; vector decode_base64(const vector input_bytes) noexcept { vector sextets(4); vector output_bytes(3); for (auto i = 0; i < 4; ++i) { sextets[i] = BASE64_CODES.find(input_bytes[i]); } output_bytes[0] = (sextets[0] << 2) | (sextets[1] >> 4); output_bytes[1] = ((sextets[1] << 4) | (sextets[2] >> 2)) & 0xFF; output_bytes[2] = ((sextets[2] << 6) | (sextets[3])) & 0xFF; return output_bytes; } void convert_from_base64(string from_filespec, string to_filespec) { ifstream ifh(filesystem::path(from_filespec).c_str()); ofstream ofh(filesystem::path(to_filespec).c_str(), ios_base::binary); if (!ifh.good()) { throw ios_base::failure("Problem opening input file!"); } if (!ofh.good()) { throw ios_base::failure("Problem opening output file!"); } int c; int count = 0; vector input_bytes(4); vector output_bytes = {}; while ((c = ifh.get()) != EOF) { if (!(isspace(c))) { input_bytes[count % 4] = c; ++count; if (count % 4 == 0) { output_bytes = decode_base64(input_bytes); int max = 3; if (input_bytes[3] == 0x3D) { --max; } if (input_bytes[2] == 0x3D) { --max; } for (auto i = 0; i < max; ++i) { ofh.put(output_bytes[i]); } } } } ifh.close(); ofh.close(); } int main(int argc, char **argv) { if (argc != 3) { cout << "Syntax: " << argv[0] << " {fromFilespec} {toFilespec}" << endl; exit(1); } string from_filespec(argv[1]); string to_filespec(argv[2]); try { convert_from_base64(from_filespec, to_filespec); } catch (ios_base::failure ex) { cout << "Error: " << Utils::exceptionMessage(ex) << endl; } return 0; }