【发布时间】:2018-04-17 06:25:38
【问题描述】:
下面的代码使用aes_128_cbc,它正确地加密了代码,但是当我把它改成aes_128_gcm时,没有输出加密。下面的代码是我原来的工作代码。我的密钥是 128 位(长度 16),而 iv 也是长度 16。
#include <stdlib.h>
#include <openssl/evp.h>
#include <openssl/aes.h>
#include <string.h>
EVP_CIPHER_CTX *ctx;
char key[]="somerandomkey123"; /*length 16*/
char output[1024];
char input[]= "Message here.";
int len;
FILE *binfile;
if(!ctx = EVP_CIPHER_CTX_new()){
(error message)
}
if(1 != EVP_EncryptInit_ex(ctx,EVP_aes_128_cbc(),NULL,key,"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\")){
(error message)
}
if(1 != EVP_EncryptUpdate(ctx,output,&len,input,strlen(input))){
(error message)
}
if(1 != EVP_EncryptFinal_ex(ctx, output+len, &len)){
(error message)
}
EVP_CIPHER_CTX_free(ctx)
/*This prints out 0 when I change cbc to gcm, but prints a correct size when I use cbc*/
printf("Output size: %d \n", len);
/*Properly writes to file when cbc used but not when gcm used. Nothing is in encrypted.bin when gcm is used when encrypted text should be there.*/
binfile = fopen("encrypted.bin","wb");
fwrite(outbuf,len,1,binfile);
当我将 EVP_aes_128_cbc() 更改为 EVP_aes_128_gcm() 时,代码不再起作用。我还将 iv 更改为长度 12(“\0\0\0\0\0\0\0\0\0\0\0\0”)。最后,我在 EVP_EncryptFinal_ex 之后添加了这个代码块:
char tag[] = "1234567890123456";
if(1 != EVP_CIPHER_CTX_ctrl(ctx,EVP_CTRL_GCM_GET_TAG,16,tag)){
(error message)
}
打印时我的最终输出大小为 0,其中没有任何内容(在原始代码中注明)。我的问题是为什么我只将 cbc 更改为 gcm 时没有得到任何加密?是由于 key/iv 大小问题还是更大的问题?
【问题讨论】:
-
您的原始代码不完整。它也有语法错误。而且你没有解释“不起作用”是什么意思?
-
嘿,对不起。我编辑了我的问题并移动了一些东西,我可能已经删除了一些信息。以上是我完全拥有的代码(可能错过了包含语句),但总的来说这就是我所拥有的。对于 cbc 它可以工作,但是将其更改为 gcm,我的输出缓冲区是空的,最后没有发生加密。我希望这个澄清会有所帮助。
-
AES 加密字节,而不是字符串。如果第一个字节变成
0x00,那么strlen将报告0。不要使用strlen,使用你现有的len变量。 -
stelen 是错字吗?
-
哎呀,我修好了。是的,那应该是strlen。如果我将缓冲区输出写入一个名为 encrypted.bin 的文件,则该文件完全为空。我将其添加到问题中以展示这一点。
标签: c authentication encryption openssl aes-gcm