Is iv optional or is there a default iv?
IV allows securely reuse the same encryption key for encrypting multiple inputs. Reusing the same key for encryption (without IV) may completely reveal the plaintext or key depending on the cipher and mode.
If you are using different keys for each message, the IV could be in theory static. However – I’d recommend to use random IV anyway. If you use the same key for multiple messages, you definitely need a random and unpredictable IV.
But didn’t mention about how to provide a iv.
The IV generally needs to be unique. Some encryption modes have stronger requirements, for the CBC mode you use the IV needs to be unpredictable – stronger term than random. (thank you Kelaka). Usually the IV is prepended to the ciphertext, as it has fixed length (16 bytes for AES) and it is needed for decryption. It is a common practice, but not any law. Often used format is
You can send the IV separately as a different parameter or payload element too, it doesn’t matter until it reaches the recipient who needs the IV to decrypt the ciphertext.
There are some standards for passing the IV, ciphertext and authentication (JWE, WS-Security, PKCS#7, CMS, ..) but usually the standards require complexity and overhead that for simple use cases it’s just simpler to pass the IV and cipher in an agreed format with the message consumer. I’d vouch for JWE if you want something standardized and simple.
btw: I see commonly ignored the authentication hash (hmac) which ensures the ciphertext is not changed.
I nontice in openssl the encrypt text always start with ‘Salted__’. Is that a agreement? And how does it save IV？
Openssl uses format
Salted__<8 byte salt><ciphertext> and then generate the encryption key and IV from the provided password and the salt. Older versions were using EVP_BytesToKey function, newer versions are using different KDF (key derivation function).
CLICK HERE to find out more related problems solutions.