我寫了一個程序,一個字符串PolarSSL AES-CBC
後我加密字符串PolarSSL AES-CBC
這是我的代碼
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <polarssl/aes.h>
#include <polarssl/havege.h>
int main()
{
char buff[2][64] = {"Who can tell me WHY?", ""};
havege_state hs;
int retval;
unsigned char IV[16];
aes_context enc_ctx;
aes_context dec_ctx;
aes_setkey_enc(&enc_ctx, "password", 256);
aes_setkey_dec(&dec_ctx, "password", 256);
havege_init(&hs);
havege_random(&hs, IV, 16);
//encrypt
aes_crypt_cbc(&enc_ctx, AES_ENCRYPT, 64, IV, buff[0], buff[1]);
havege_random(&hs, IV, 16);
//decrypt
aes_crypt_cbc(&dec_ctx, AES_DECRYPT, 64, IV, buff[1],buff[0]);
printf("After decrypt:%s\n", buff[0]);
return 0;
}
加密但是當我運行它,我不能解密字符串,解密後我剛收到錯誤的文字。
我不明白AES算法,因爲我的英文很糟糕,閱讀一些文章太難了。
------------------------- Added by midCat ------------------ --------------------------
我跟着你的意見,並改變我的代碼 現在我使用相同的IV和256位關鍵,這是新代碼
int main()
{
char buff[2][64] = {"ABCDEFGHIJKLMN", ""};
havege_state hs;
int retval;
unsigned char IV[16];
unsigned char IV2[16];
unsigned char key[32];
aes_context enc_ctx;
aes_context dec_ctx;
havege_init(&hs);
havege_random(&hs, IV, 16);
havege_random(&hs, key, 32);
strncpy(IV, IV2, 16); //copy IV
aes_setkey_enc(&enc_ctx, key, 256);
aes_setkey_dec(&dec_ctx, key, 256);
//encrypt
aes_crypt_cbc(&enc_ctx, AES_ENCRYPT, 64, IV, buff[0], buff[1]);
printf("Before encrypt:%s\n", buff[0]);
//decrypt
aes_crypt_cbc(&dec_ctx, AES_DECRYPT, 64, IV2, buff[1],buff[0]);
printf("After decrypt:%s\n", buff[0]);
return 0;
}
我編譯它,並運行多次,得到了相同的輸出:
Before encrypt:ABCDEFGHIJKLMN
After decrypt:ABCDEFGHYC
LMN
如何得到IV
?
AES適用於字節而不是字符..有一個細微的區別..您不能使用strncpy()來複制IV。您必須使用memcpy()作爲IV ** CAN **包含NULL字符。其餘的,這段代碼是可以的(並且可以在我的機器上運行)。 – Paul
你也換了源和目標操作數,你想使用memcpy(IV2,IV,sizeof(IV)) – dnaq