[英]C - OpenSSL with AES-256 and CFB mode
I am working on Ubuntu 14.10 and I am trying to get the same output using C and OpenSSL that I would get using the command: 我正在使用Ubuntu 14.10,并且正在尝试使用C和OpenSSL获得与使用以下命令相同的输出:
openssl enc -aes-256-cfb8 -in test -out test.enc -K $key -iv $iv
I have been working on this for two days and not getting it, the encryption works but it is not the one I am supposed to get. 我已经进行了两天的工作,但是没有得到加密,它可以工作,但是不是我应该得到的。
My code is: 我的代码是:
int outlen, inlen;
unsigned char inbuf[BUFSIZE] , outbuf[BUFSIZE];
strcpy(inbuf,text);
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, EVP_aes_256_cfb8(), NULL, key, iv);
int i =0;
int n = strlen(text);
for(i; i < n; i++) {
if(!EVP_EncryptUpdate(&ctx, outbuf, &outlen, inbuf, 1))
return 0;
}
if(!EVP_EncryptFinal(&ctx, outbuf, &outlen))
return 0;
EVP_CIPHER_CTX_cleanup(&ctx); P_EncryptFinal(&ctx, outbuf, &outlen))
return 0;
EVP_CIPHER_CTX_cleanup(&ctx); i < n; i++) {
if(!EVP_EncryptUpdate(&ctx, outbuf, &outlen, inbuf, 1))
return 0;
}
if(!EVP_EncryptFinal(&ctx, outbuf, &outlen))
return 0;
EVP_CIPHER_CTX_cleanup(&ctx);
Thank You! 谢谢!
You are encrypting the same byte over and over again. 您一次又一次地加密相同的字节。 In EVP_EncryptUpdate, you have to move the inbuf pointer along across each input byte, and you have to move the outbuf pointer along to fresh memory.
在EVP_EncryptUpdate中,您必须沿每个输入字节移动inbuf指针,并且必须将outbuf指针移动至新的内存。 I made minor changes to your code (and completed it enough to run):
我对您的代码进行了微小的更改(并完成了足以运行的代码):
#include <stdio.h>
#include <openssl/ssl.h>
#define BUFSIZE 256
int doit(char* text, char* key, char* iv)
{
int outlen, inlen;
unsigned char inbuf[BUFSIZE] , outbuf[BUFSIZE];
strcpy(inbuf,text);
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, EVP_aes_256_cfb8(), NULL, key, iv);
int i =0;
int n = strlen(text);
unsigned char* p = outbuf;
for(i; i < n; i++) {
if(!EVP_EncryptUpdate(&ctx, p, &outlen, &inbuf[i], 1))
return 0;
p += outlen;
}
if(!EVP_EncryptFinal(&ctx, p, &outlen))
return 0;
p += outlen;
EVP_CIPHER_CTX_cleanup(&ctx);
outlen = p - outbuf;
for (n = 0; n < outlen; n++)
printf("%c", outbuf[n] & 0xff);
}
int main()
{
char* key = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
char* iv = "BBBBBBBBBBBBBBBB";
doit("hello world", key, iv);
}
The C code wants bytes for key and IV, but the openssl command line wants hex chars. C代码想要用于key和IV的字节,但是openssl命令行想要十六进制字符。 This command line will get you the same result as the above C code:
此命令行将为您提供与上述C代码相同的结果:
openssl enc -aes-256-cfb8 -in test -out test.enc -K 4141414141414141414141414141414141414141414141414141414141414141 -iv 42424242424242424242424242424242
Of course, you need to set up the exact same plaintext: 当然,您需要设置完全相同的明文:
$ echo "hello world" > test
$ truncate --size 11 test # remove newline at end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.