KillPinguin
KillPinguin

Reputation: 410

AES256 Libgcrypt Invalid Key Length

I'm trying to encrypt and decrypt Files using AES256 from libgcrypt. (see doc)

To generate the 256-Bit Key, I'm hashing a user-defined string (argv[1]) with SHA256. This works perfectly fine, but when using it as a key, the library fails with Invalid key length.

See code snippet below:

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);

Do I have to use a null terminated string? I don't want to allocate more memory for the hash (which would probably be needed for the null byte), because it should be placed in SECUREMEM.

Upvotes: 1

Views: 693

Answers (1)

KillPinguin
KillPinguin

Reputation: 410

Ok I found my error:
gcry_cipher_setkey() expects the length in bytes, so 32 instead of 256.

From the 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.

Upvotes: 2

Related Questions