|
| 1 | +#include "headers/encryption.h" |
| 2 | +#include <QDebug> |
| 3 | + |
| 4 | +using namespace CryptoPP; |
| 5 | + |
| 6 | +std::string Encryption::encrypt(std::string content, std::string passphrase) { |
| 7 | + AutoSeededRandomPool prng; |
| 8 | + byte iv[AES::BLOCKSIZE]; |
| 9 | + prng.GenerateBlock(iv, sizeof(iv)); |
| 10 | + std::string ivString(reinterpret_cast< char const* >(iv)); |
| 11 | + SecByteBlock key(AES::MAX_KEYLENGTH+AES::BLOCKSIZE); |
| 12 | + |
| 13 | + std::string encrypted, output; |
| 14 | + |
| 15 | + try { |
| 16 | + HKDF<SHA256> hkdf; |
| 17 | + hkdf.DeriveKey(key, key.size(), (const byte*) passphrase.data(), passphrase.size(), (const byte*) ivString.c_str(), AES::BLOCKSIZE, NULL, 0); |
| 18 | + |
| 19 | + CTR_Mode<AES>::Encryption encryption; |
| 20 | + encryption.SetKeyWithIV(key, AES::MAX_KEYLENGTH, key+AES::MAX_KEYLENGTH); |
| 21 | + |
| 22 | + StringSource(content, true, new StreamTransformationFilter(encryption, new StringSink(encrypted))); |
| 23 | + |
| 24 | + std::string finalStr = "encrypted" + ivString + "__ENDIV" + encrypted; |
| 25 | + |
| 26 | + StringSource(finalStr, true, new Base64Encoder(new StringSink(output))); |
| 27 | + } catch (const Exception& ex) { |
| 28 | + qDebug() << ex.what(); |
| 29 | + } |
| 30 | + |
| 31 | + return output; |
| 32 | +} |
| 33 | + |
| 34 | +std::string Encryption::decrypt(std::string content, std::string passphrase) { |
| 35 | + std::string base64Decoded, ivString, decrypted; |
| 36 | + |
| 37 | + StringSource(content, true, new Base64Decoder(new StringSink(base64Decoded))); |
| 38 | + |
| 39 | + if (base64Decoded.substr(0, 9) != "encrypted") |
| 40 | + return ""; |
| 41 | + |
| 42 | + unsigned first = base64Decoded.find("encrypted") + 9; // 9 = encrypted length |
| 43 | + unsigned last = base64Decoded.find("__ENDIV"); |
| 44 | + ivString = base64Decoded.substr(first, last - first); |
| 45 | + |
| 46 | + first = base64Decoded.find("__ENDIV") + 7; // 7 = __ENDIV length |
| 47 | + |
| 48 | + base64Decoded = base64Decoded.substr(first); |
| 49 | + |
| 50 | + SecByteBlock key(AES::MAX_KEYLENGTH + AES::BLOCKSIZE); |
| 51 | + |
| 52 | + try { |
| 53 | + HKDF<SHA256> hkdf; |
| 54 | + hkdf.DeriveKey(key, key.size(), (const byte*)passphrase.data(), passphrase.size(), (const byte*) ivString.c_str(), AES::BLOCKSIZE, NULL, 0); |
| 55 | + |
| 56 | + CTR_Mode<AES>::Decryption decryption; |
| 57 | + decryption.SetKeyWithIV(key, AES::MAX_KEYLENGTH, key + AES::MAX_KEYLENGTH); |
| 58 | + |
| 59 | + StringSource(base64Decoded, true, new StreamTransformationFilter(decryption, new StringSink(decrypted))); |
| 60 | + } catch (const Exception& ex) { |
| 61 | + qDebug() << ex.what(); |
| 62 | + } |
| 63 | + |
| 64 | + return decrypted; |
| 65 | +} |
0 commit comments