Reputation: 16755
I need to encrypt a file via AES-256-CBC
but with textual password instead of a key and iv. I think, that there is no any way to do that so I must convert my textual password to the byte array, expand it somehow to the key length and treat it as a key, and then.. I don't know what to do with the initialization vector. So the question is how to correctly do this?
P.S. Note please that I need to do this not with command line openssl but with the library.
Upvotes: 3
Views: 1745
Reputation: 1628
If all you want to do is convert a text password for use with the new createCipher createDecipher APIs (which add "iv"), then the conversion info is clear (see Wagner's answer in the other response).
However, the reason these APIs are being deprecated is essential to understanding why you should use them differently. For that reason, I'd recommend reading something like this strong article on encryption using the latest Node APIs. Short article, but very clear and yet secure approach.
http://vancelucas.com/blog/stronger-encryption-and-decryption-in-node-js/
I say this because it can be deceptively easy to move from one API to another without understanding the reason for the change, and thus, lose the benefit of the intended change.
In this post and the link given, the platform in question is Node, but the issue is the same on any platform. You shouldn't treat the IV as just a template parameter that you give away to the user. Make it random. The benefits of this are explained in the link, as I've said.
Upvotes: 1
Reputation: 5674
Victor, you are in the right direction. The password, in this case, is just something that you can hash and obtain the key that will be used for encrypting with AES. The IV (initialization vector) is something that can be public and is not part of your password. The function EVP_EncryptInit_ex()
has a parameter for it. It will be something like this:
EVP_CIPHER_CTX cryptContext;
EVP_CIPHER_CTX_init(&cryptContext);
EVP_EncryptInit_ex(&cryptContext, EVP_aes_256_cbc(), 0, key, iv);
EVP_EncryptUpdate(&cryptContext, output, &outputLength, input, inputLength);
EVP_CIPHER_CTX_cleanup(&cryptContext);
Use the function EVP_BytesToKey()
in order to "convert" your password to a key:
uint8_t key[AES_256_CBC_KEY_SIZE];
uint8_t iv[AES_256_CBC_IV_SIZE];
EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha256(), salt, password, passwordLength, 1, key, iv);
Upvotes: 1