2017-08-24 77 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.