【发布时间】:2015-12-02 21:57:52
【问题描述】:
我正在尝试使用 AES-GCM。我的加密代码有效,但是当我尝试使用相同的 IV 和密钥加密相同的纯文本时,我得到了相同的结果。我的 GCM 代码:
EVP_CIPHER_CTX *ctx;
int outlen, tmplen;
unsigned char outbuf[1024];
ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, sizeof(gcm_iv), NULL);
EVP_EncryptInit_ex(ctx, NULL, NULL, gcm_key, gcm_iv);
EVP_EncryptUpdate(ctx, NULL, &outlen, gcm_aad, sizeof(gcm_aad));
EVP_EncryptUpdate(ctx, outbuf, &outlen, gcm_pt, sizeof(gcm_pt));
printf("Ciphertext:\n");
BIO_dump_fp(stdout, outbuf, outlen);
EVP_EncryptFinal_ex(ctx, outbuf, &outlen);
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, outbuf);
printf("\n\n\n");
EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, sizeof(gcm_iv), NULL);
EVP_EncryptInit_ex(ctx, NULL, NULL, gcm_key, gcm_iv);
EVP_EncryptUpdate(ctx, NULL, &outlen, gcm_aad, sizeof(gcm_aad));
EVP_EncryptUpdate(ctx, outbuf2, &outlen2, gcm_pt, sizeof(gcm_pt));
printf("Ciphertext:\n");
BIO_dump_fp(stdout, outbuf2, outlen2);
EVP_EncryptFinal_ex(ctx, outbuf2, &outlen2);
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, outbuf2);
EVP_CIPHER_CTX_free(ctx);
如果在第二次加密中我将删除 init_ex、ctx_ctrl 等,我的密文将是一个空字符串。
但如果我使用 EVP_aes_256_ctr,那么下一次加密会给我新的密文。 EVP_aes_256_ctr 的代码:
EVP_CIPHER_CTX *ctx;
int outlen, tmplen;
unsigned char outbuf[1024];
ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), NULL, NULL, NULL);
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, sizeof(gcm_iv), NULL);
EVP_EncryptInit_ex(ctx, NULL, NULL, gcm_key, gcm_iv);
EVP_EncryptUpdate(ctx, outbuf, &outlen, gcm_pt, sizeof(gcm_pt));
BIO_dump_fp(stdout, outbuf, outlen);
EVP_EncryptFinal_ex(ctx, outbuf, &outlen);
printf("\n\n\n");
EVP_EncryptUpdate(ctx, outbuf, &outlen, gcm_pt, sizeof(gcm_pt));
printf("Ciphertext:\n");
BIO_dump_fp(stdout, outbuf, outlen);
EVP_EncryptFinal_ex(ctx, outbuf, &outlen);
EVP_CIPHER_CTX_free(ctx);
据我了解,这两种模式都在计数器模式下工作,因此计数器将为相同的 IV、密钥、明文生成不同的密码。那么为什么在 GCM 模式下密文是一样的呢?
【问题讨论】:
-
你为什么不期望用相同的密钥和 IV 加密相同的明文来产生相同的值呢?您想将明文作为第二个块重复吗?
-
是的。我希望数据可以重复。而且据我所知,我的安全性不会被破坏,密码必须不同
标签: c++ c encryption openssl aes