AES256 Libgcrypt 无效密钥长度

AES256 Libgcrypt Invalid Key Length

我正在尝试使用来自 libgcrypt 的 AES256 加密和解密文件。 (参见 doc

为了生成 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 中。

好的,我发现了我的错误:
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.