2017-08-24 140 views
1

我試圖使用libgcrypt中的AES256加密和解密文件。 (請參閱docAES256 Libgcrypt密鑰長度無效

要生成256位密鑰,我使用SHA256散列用戶定義的字符串(argv[1])。這很好用,但是當它用作密鑰時,庫會以Invalid key length失敗。

見代碼片段如下:

gcry_md_hd_t hd; 
gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_SECURE); 

gcry_md_write(hd, argv[1], strnlen(argv[1], P_DIARY_MAXPWDLEN)); 
unsigned char * hash = gcry_md_read(hd, GCRY_MD_SHA256); 

gcry_cipher_hd_t cipher; 
gcry_cipher_open(&cipher, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, GCRY_MD_FLAG_SECURE); 
gcry_cipher_setkey(cipher, hash, 256); 

我必須用一個空結束的字符串?我不想爲散列分配更多內存(這可能需要空字節),因爲它應該放置在SECUREMEM中。

回答

2

確定我發現我的錯誤:
gcry_cipher_setkey()預計字節長度,如此32代替256

doc

Function: gcry_error_t gcry_cipher_setkey (gcry_cipher_hd_t h, const void *k, size_t l)

[...] The length l (in bytes) of the key k must match the required length of the algorithm set for this context or be in the allowed range for algorithms with variable key size. The function checks this and returns an error if there is a problem. A caller should always check for an error.