AES CTR OpenSSL 命令行不匹配 EVP_aes_128_ctr C 代码

AES CTR OpenSSL command line does not match EVP_aes_128_ctr C code

CTR-AES256 Encrypt does not match OpenSSL -aes-256-ctr <-- 这个 post 没有帮助

我尝试了以下用于 AES-128-CTR 加密的 Openssl EVP 函数的 C 实现,但与命令行 OpenSSL 结果相比,我得到的结果不正确。

奇怪的是,当我尝试使用更大尺寸的明文(600 字节或更多)时,C 代码和命令行之间只有最后 600 字节的密码不同。如果需要,我也可以将结果粘贴到此处。

AES-128-CTR 的 C 代码实现

static const unsigned char key[16] = {
    0x00, 0x01, 0x02, 0x03, 
    0x04, 0x05, 0x06, 0x07, 
    0x08, 0x09, 0x0a, 0x0b, 
    0x0c, 0x0d, 0x0e, 0x0f, 
};

static const unsigned char iv[16] = {
    0x01, 0x23, 0x45, 0x67, 
    0x89, 0xab, 0xcd, 0xef, 
    0x88, 0x88, 0x88, 0x88, 
    0xC0, 0x00, 0x00, 0x00, 
};

FILE *fp_output = fopen("cipherCode.bin", "wb");

// Encrypt Plaintext

EVP_CIPHER_CTX *ctx;
int outlen;
unsigned char cipher[size];

if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

if(!(EVP_EncryptInit_ex(ctx, EVP_aes_128_ctr(), NULL, key, iv))) handleErrors();

if(!(EVP_EncryptUpdate(ctx, cipher, &outlen, plaintext, size))) handleErrors();

if(!(EVP_EncryptFinal_ex(ctx, cipher + outlen, &outlen))) handleErrors();

/*---Edit----

// EVP_CIPHER_CTX_set_padding(ctx, 0); <-- removed this as it isnt necessary 

-----------*/

EVP_CIPHER_CTX_free(ctx);

// Write result cipher into output file
fwrite((unsigned char *)&cipher[0], outlen, 1, fp_output);
fclose(fp_output);

OpenSSL 命令行:

openssl enc -aes-128-ctr -in plaintext.bin -out cipherCL.bin -K 000102030405060708090a0b0c0d0e0f -iv 0123456789abcdef88888888c0000000 -p -nopad

两者使用相同的明文、密钥和 IV。

输入:

Plaintext:

0000000 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff

输出:

Hexdiff(为清楚起见缩短):

Visuel HexDiff v 0.0.53 by tTh 2007                             dec   7bits  

0   00 00 00 00 00 00 00 00 10 90 66 01 00 00 00 00              f     

** cipherCode.bin                                    16        0   0%      

0   1e a4 43 3f d8 4c 8c b7 1a e7 f0 af 85 0c d2 c2      C? L

** cipherCL.bin                                   16        0   0%      

我推荐你使用这个免费的 AES 库 link

它是用 c 语言编写的 AES ECB、CTR 和 CBC 加密算法的小型可移植实现。它包含您需要的一切,而且非常简单。 顺便说一句,您可以通过在 aes.h.

中定义符号 AES192 或 AES256 来使用 192 或 256 位覆盖默认的 128 位密钥大小

我在我的程序中发现了这个问题。我没有将密码变量定义为静态的。现在我将其定义为静态,正确的密码数据已写入文件。

为什么静态有效? 我调用了一个加密函数来计算密码,然后 return 密码。由于密码没有被声明为static,它在退出函数后失去了它的价值,因此数据returned与密码中的数据不同。将cipher声明为static后,函数调用后保留cipher的值,并在文件中写入正确的信息。