OpenSSL AES256 cbc加密

时间:2011-12-18 19:21:51

标签: iphone openssl aes

我试图在互联网上找到一个适当的例子好几天但没有成功。我尝试用密钥加密简单字符串(Hello World),然后解密结果。 但是,解密结果与原始文本无关。有人能指点我的方向吗?

我制作的代码:

AES_KEY aes_decryptKey;
AES_KEY aes_encryptKey;

const unsigned char mykey[] = {0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa};
unsigned char encrypted ;
unsigned char iv[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};    
unsigned char decrypted;

AES_set_encrypt_key(mykey, 256, &aes_encryptKey);
AES_set_decrypt_key(mykey, 256, &aes_decryptKey);

const unsigned char original[]  = {0x48,0x65,0x6c,0x6c,0x6f,0x2c,0x77,0x6f,0x72,0x6c,0x64,0x21};

AES_cbc_encrypt(original, &encrypted, sizeof(original), &aes_encryptKey, iv, 0);

AES_decrypt( &encrypted, &decrypted, &aes_decryptKey);

NSLog(@"ORIGINAL: \"%s\"\n",original);
NSLog(@"ENCRYPTED: \"%s\"\n",&encrypted);
NSLog(@"DECRYPTED: \"%s\"\n",&decrypted);

2 个答案:

答案 0 :(得分:1)

您正在解密两次 - AES_cbc_encrypt的最后一个0参数应为1或AES_ENCRYPT

此外,您正在覆盖加密和解密字符,而这些字符应该足够大,以容纳原始的加密大小。而不是:

unsigned char encrypted;
...
AES_cbc_encrypt(original, &encrypted, ...

使用类似的东西:

unsigned char encrypted[32];
...
AES_cbc_encrypt(original, encrypted, ...

还有类似的东西:

unsigned char decrypted[32];
....
AES_decrypt(encrypted, decrypted, &aes_decryptKey);

点击此链接:http://marc.info/?l=openssl-users&m=122919878204439。我还不能保证所有这一切 - 我会在有空的时候回来编辑我的答案。

答案 1 :(得分:1)

吉姆,谢谢你的帮助。

似乎我不得不提出一个问题来找到答案。 经过多天的努力,这就是我想出来的:

    unsigned char inbuf[1024]="Hello,world!";
unsigned char encbuf[1024];

unsigned char key32[] = {0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa};
unsigned char deckey32[] = {0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa}
;
unsigned char iv[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};    
unsigned char deciv[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};    

AES_KEY aeskey;
AES_KEY aesdeckey;

//Now enrypt
memset(encbuf, 0, sizeof(encbuf));
AES_set_encrypt_key(key32, 32*8, &aeskey);
AES_cbc_encrypt(inbuf, encbuf, 16, &aeskey, iv, AES_ENCRYPT);

//Now decrypt
unsigned char decbuf[1024];
memset(decbuf, 0, sizeof(decbuf));

AES_set_decrypt_key(deckey32, 32*8, &aesdeckey);
AES_cbc_encrypt(encbuf, decbuf, 16, &aesdeckey, deciv, AES_DECRYPT);


//Display the results
NSLog(@"ORIGINAL: \"%s\"\n", inbuf);
NSLog(@"ENCRYPTED: \"%s\"\n", encbuf);
NSLog(@"DECRYPTED: \"%s\"\n", decbuf);

return;

对这些人的信任(在吉姆之后):http://www.mail-archive.com/openssl-users@openssl.org/msg50142.html

关键是使用AES_cbc_encrypt来解密。