I'm developing an application that communicates with a DB located on a VPS. I need to store an information, encrypted with AES-256, in my DB.
If I'm correct, when I encrypt, there's an IV parameter which is generated and is different for each encryption. However when I decrypt, I don't have this parameter because I only have the key and the encrypted text in the DB.
What can I do to solve this problem?
After the first block is decrypted, you still have an intermediate value which has been XORed with the plaintext — without this, you have little hope of recovering the plaintext. However, you do not need the IV to decrypt subsequent blocks.
Yes, you must provide the same IV for encryption and decryption.
You need to use the same IV for encryption and decryption.
You must store the initialization vector somewhere. Because, conceptually, in CBC mode the IV is the "zeroth" block of ciphertext, some people store it as prefix to the ciphertext. Most low-level decryption libraries don't expect this, however, so the application usually needs to provide a wrapper that handles adding this prefix after encryption and removing it before decryption.
Ideally, you should store encrypted values with some metadata that specifies the encryption algorithm that was used, any parameters that are needed, and indicates what key (note below!) is used. This would include the IV for a block cipher that used CBC. A standard format for this is the Cryptographic Message Syntax, or PKCS #7. Because it's a standard, you will likely have several options for an open-source library to handle the format.
By including this metadata, you can do things like rotate keys over time, or migrate data to new algorithms. You don't have to have every value encrypted the same way with the same key.
Note: When I say that the metadata indicates the key used, this doesn't mean the key itself is included, of course! For pre-shared keys, it's just an label that tells you which key on your big keyring will decrypt the payload. For password-based encryption, there would be information about how to derive a proper key from the implied password.
You can concatenate the IV with the ciphertext (its length is known and constant), or you can store them next to each other in the DB. The IV isn't a secret; it just ensures that the block cipher is initialized differently per encryption so that brute-forcing one file decryption doesn't compromise all the others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With