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.