c - AES256 Libgcrypt 无效 key 长度

标签 c aes libgcrypt

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

为了生成 256 位 key ,我使用 SHA256 散列用户定义的字符串 (argv[1])。这工作得很好,但是当将它用作 key 时,库失败并显示 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.

关于c - AES256 Libgcrypt 无效 key 长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45856799/

相关文章:

c - scanf 之后 fgets 不起作用

c - 如何以可以使用链接列表元素执行命令的方式解析链接列表元素

java - KeyGenerator 返回 java.security.NoSuchAlgorithmException : no such algorithm for BouncyCaSTLe

linux - openSUSE Linux : No Provider for libglib-dev libgcrypt-dev found

c aes256 填充与 pkcs#7 标准

c - 在GNU中设置标准信号SIGIO

c - 没有循环的递归冒泡排序

java - 使用 AES 缓存用户密码 -- BadPaddingException

c# - 使用 SharpAESCrypt 加密字符串

c - 在 C 中从用户那里获取*安全*输入的最佳方式是什么?