【发布时间】:2018-06-15 23:28:20
【问题描述】:
CTR-AES256 Encrypt does not match OpenSSL -aes-256-ctr
我为 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%
【问题讨论】:
-
在您的代码摘录中包含您如何声明
key和iv。 -
同时展示你的代码是如何写入输出文件的;四分之三的字节为零的“密文”实际上是不可能的。仅供参考,在进行加密(或解密)后调用
_set_padding是没用的,但 CTR 是一种流模式,无论如何都不使用填充。 -
@LukeJoshuaPark dave_thompson_085 请检查编辑。谢谢。
标签: c encryption openssl aes encryption-symmetric