1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| #include <openssl/evp.h> #include <vector> std::string AES128ECBEncrypt(const std::string& base64key, const std::string& str) { std::vector<unsigned char> key; if (!Base64Decode(base64key, key)) return "";
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); int encLen = 0; int outlen = 0; size_t outsize = ((str.size() / 16)+1) * 16; std::vector<unsigned char> encData(outsize);
EVP_CipherInit_ex(ctx, EVP_aes_128_ecb(), NULL, key.data(), NULL, 1); EVP_CipherUpdate(ctx, encData.data(), &outlen, (const unsigned char*)str.c_str(), (int)str.size()); encLen = outlen; EVP_CipherFinal_ex(ctx, encData.data() + outlen, &outlen); encLen += outlen; EVP_CIPHER_CTX_free(ctx); return std::move(Base64Encode(encData.data(), encLen)); }
std::string AES128ECBDecrypt(const std::string& base64Key, const std::string& base64str) { std::vector<unsigned char> buffer; if (!Base64Decode(base64str, buffer)) { return ""; }
std::vector<unsigned char> key; if (!Base64Decode(base64Key, key)) { return ""; }
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); int encLen = 0; int outlen = 0;
BUFFER encData(buffer.size());
EVP_CipherInit_ex(ctx, EVP_aes_128_ecb(), NULL, key.data(), NULL, 0); EVP_CipherUpdate(ctx, encData.data(), &outlen, buffer.data(), (int)buffer.size()); encLen = outlen; EVP_CipherFinal(ctx, encData.data() + outlen, &outlen); encLen += outlen; EVP_CIPHER_CTX_free(ctx); return std::move(std::string((char*)encData.data(), encLen)); }
|