Hello Jinze. The issue doesn't come from OpenSSL. It comes from at least two buffer overruns.
In aesEncrypt: > > ret = EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, (const unsigned > char*)key.c_str(), NULL); You use key.c_str() to set the key. However, key here is "input": > > if (!aesEncrypt(content, "input", encrypted_content)) return -1; key.c_str() returns a buffer of size 6: "input" plus the null-terminated byte. However, EVP_aes_128_ecb expects a buffer of at least 16 bytes. Therefore, this is UB: you don't control the 10 bytes after the buffer returned by key.c_str(). Same with aesDecrypt: > ret = EVP_DecryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, (const unsigned > char*)key.c_str(), NULL); > if (!aesDecrypt(encrypted_content, "input", decrypted_content)) { If you set "input" to "AAAAAAAAAAAAAAAA" ("A" x 16), it works. The main issue here is that you use the wrong container for storing your key materials and your buffers. You should use "std::vector<std::byte>" (or "std::vector<uint8_t>") with std::vector::data(). Regards, > On 12 Nov 2022, at 11:25, WuJinze via openssl-users > <openssl-users@openssl.org> wrote: > > sorry for my mistake. I found that the gist url can not display well in mail > and here is the url: > https://gist.github.com/GoGim1/77c9bebec1cc71cea066515b4623a051 > > WuJinze > 294843...@qq.com > > > ------------------ Original ------------------ > From: "WuJinze" <294843...@qq.com>; > Date: Sat, Nov 12, 2022 06:17 PM > To: "openssl-users"<openssl-users@openssl.org>;Subject: OpenSSL AES > Decryption fails randomly C++ > > Dear OpenSSL Group, > Greetings. I was working on writing simple aes encrypt/decrypt wrapper > function in c++ and running into a strange problem. The minimal reproducible > examples in gist seems working fine but when i uncomment lines 90-92, it will > fail to decrypt randomly. Can someone help me to figure out what's wrong with > the code? > Here is my code: OpenSSL AES Decryption fails randomly C++ (github.com). > OpenSSL version is OpenSSL 1.1.1f. G++ version is 9.4.0. > Regards, > Jinze