c - 使用具有不同 key 的 AES 得到相同的短加密结果

标签 c openssl aes

我有一个纯文本

unsigned char plaintext[] = "嗨,这是第一个试验";

对于按键,不要使用以下内容:

unsigned char key[16] = "azertyuopqsdfg";

我决定使用大量它们,例如“dog”,“azkier”,“jfieifdragon”,...

到目前为止我的代码如下所示:

unsigned char *aes_encrypt(unsigned char *plaintext, unsigned char *key)
{
    EVP_CIPHER_CTX *ctx;
    ctx = EVP_CIPHER_CTX_new();
    unsigned char iv[16] = "0000000000000000";

    int c_len = strlen(plaintext) + AES_BLOCK_SIZE;
    int f_len = 0;
    unsigned char *ciphertext = malloc(c_len);

    EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv);

    EVP_EncryptUpdate(ctx, ciphertext, &c_len, plaintext, strlen(plaintext));

    EVP_EncryptFinal_ex(ctx, ciphertext+c_len, &f_len);

    EVP_CIPHER_CTX_free(ctx);

    return ciphertext;
}

当我编译并运行时,输出如下所示:

the key: dog
the plain: Hi, this is trial number one
ciphertext: 157a320

the key: azkier
the plain: Hi, this is trial number one
ciphertext: 157a320

.....

我的问题是:

为什么即使我使用不同的 key ,我总是得到相同的密文?

另外,为什么密文这么短?我的明文相当长。

谢谢。

更新 --> 我调用 aes_encrypt 的方式是这样的:

unsigned char plaintext[] = "Hi, this is trial number one";
unsigned char *cipher;
cipher = aes_encrypt(plaintext, "dog");
printf("The cipher is: %x\n", cipher);
free(cipher);

unsigned char *cipher;
cipher = aes_encrypt(plaintext, "azkier");
printf("The cipher is: %x\n", cipher);
free(cipher);

最佳答案

在您的测试代码中:

printf("The cipher is: %x\n", cipher);

嗯,当然这是行不通的 - %xcipher地址打印为十六进制,而不是它的内容。如果您想要转储 cipher 的内容,您需要自己循环遍历每个字节。

此外,EVP_EncryptInit_exkey 参数是一个固定长度的缓冲区,其大小根据您使用的密码设置。 它不是字符串。传递短字符串可能会导致不可预测的行为,因为字符串结束后存储的任何数据都可能用作 key 的一部分。

关于c - 使用具有不同 key 的 AES 得到相同的短加密结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40700429/

相关文章:

mysql - 将 AESCipher 对象存储在 mySQL 中

ios - 如何在请求中使用 SSL,swift 3

ssl - 如何使用 vertx 连接 http 服务器 websocket 和 ssl?

ssl - Openssl 重新协商失败

java - AES - 生成 key 并加载它会产生无效 key 异常

java - 尝试使用 AES 加密和解密字符串时出现 IllegalBlockSizeException

c - 链表头始终设置为 NULL

C 数组 malloc() VS {}

c - 数据在 C union 中的位置是否有任何标准?

c - 为什么会出现段错误?