I'm trying to encrypt/decrypt some string data. I use Cipher. I've been wondering if it's necessary to use IV in order to encrypt data. If you can use Cipher without IV, then how to do that?
I got some code here: Here is code to encrypt data:
fun encrypt(cipher: Cipher, plainText: ByteArray): String {
val enc = cipher.doFinal(plainText)
return Base64.encodeToString(
enc,
Base64.DEFAULT
) + separator + Base64.encodeToString(
cipher.iv,
Base64.DEFAULT
)
}
And here is code for decryption:
fun decrypt(cipher: Cipher, encrypted: String): String {
return cipher.doFinal(
Base64.decode(
encrypted,
Base64.DEFAULT
)
).toString(Charsets.UTF_8)
}
Initialization of Decryption:
cipherDec.init(
Cipher.DECRYPT_MODE, key, IvParameterSpec(
Base64.decode(
IV.toByteArray(Charsets.UTF_8),
Base64.DEFAULT
)
)
Initialization of Encryption:
cipherEnc.init(Cipher.ENCRYPT_MODE, key)
First of all, you can't simply not use the IV (Initialization Vector), as the ciphers working in stronger modes are always designed to require one. The purpose of an IV is to generate different ciphertexts for same plaintexts. The usual approach is to use a strong random number generator to get as many bytes of IV as necessary, than attach the IV to the ciphertext (usually in front of it), and then use the IV to decrypt. Yes, IV does not need to be encrypted or hidden. It just needs to be there.
So what if you don't want or need the IV (you may not need the IV if every plaintext is different because of the plaintext domain or business need). You can use a constant value for the IV (like an array of zero bytes). Then you would not need to attach the IV to the ciphertext. But note - don't do that unless you know exactly what you are doing. Use a random IV instead.
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