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

标签 c encryption openssl aes encryption-symmetric

CTR-AES256 Encrypt does not match OpenSSL -aes-256-ctr <-- 这篇文章没有帮助

我尝试了 Openssl EVP 函数的以下 C 实现来进行 AES-128-CTR 加密,但与命令行 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

两者使用相同的明文、 key 和 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%      

最佳答案

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

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

关于c - AES CTR OpenSSL 命令行与 EVP_aes_128_ctr C 代码不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50883780/

相关文章:

c - Visual Studio 2013 无法识别字符串?

c++ - OpenSSL 解密 - EVP_DecryptFinal_ex 失败

c - C语言十进制转二进制

php - mcrypt_decrypt() 错误更改 key 大小

c# - 加密c#和mysql之间的数据流量

PHP : Form example which will encrypt query string (GET) (data hiding rather than security)

python - 如何在Web应用程序中读取数字证书? (灯)

c++ - C++ 套接字连接中的 OpenSSL(HTTPS 客户端)

c++ - 错误 openSSL 似乎缺乏椭圆曲线加密?这是什么意思以及如何解决?

c - 在 WPF tabControl 中,如何从对象类型中动态选择标签页?