【问题标题】:AES CTR OpenSSL command line does not match EVP_aes_128_ctr C codeAES CTR OpenSSL 命令行与 EVP_aes_128_ctr C 代码不匹配
【发布时间】: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%      

【问题讨论】:

  • 在您的代码摘录中包含您如何声明 keyiv
  • 同时展示你的代码是如何写入输出文件的;四分之三的字节为零的“密文”实际上是不可能的。仅供参考,在进行加密(或解密)后调用 _set_padding 是没用的,但 CTR 是一种流模式,无论如何都不使用填充。
  • @LukeJoshuaPark dave_thompson_085 请检查编辑。谢谢。

标签: c encryption openssl aes encryption-symmetric


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我建议您使用这个免费的 AES 库 link

    它是用 c 编写的 AES ECB、CTR 和 CBC 加密算法的小型便携式实现。它包含您需要的一切,而且非常简单。 顺便说一句,您可以通过在aes.h 中定义符号 AES192 或 AES256 来用 192 或 256 位覆盖 128 位的默认密钥大小。

    【讨论】:

    • 这没有回答问题。
    猜你喜欢
    • 2017-08-08
    • 2018-05-10
    • 2021-05-30
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多