Kotlin
AES
Learn AES encryption with javax.crypto.
Symmetric encryption with AES
AES is a symmetric encryption algorithm; the same key encrypts and decrypts. The Cipher class uses the AES/CBC/PKCS5Padding transformation.
Example: val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"). The key comes from SecretKeySpec; the IV from IvParameterSpec. Use ENCRYPT_MODE to encrypt and DECRYPT_MODE to decrypt. AES provides both confidentiality and efficiency.
ENCRYPT_MODE and DECRYPT_MODE
cipher.init(Cipher.ENCRYPT_MODE, key, iv) prepares for encryption; cipher.init(Cipher.DECRYPT_MODE, key, iv) for decryption. doFinal performs the operation.
Example: encrypt val enc = cipher.doFinal(plain.toByteArray()), decrypt val dec = cipher.doFinal(enc). String(dec) gives the original text. The IV must stay the same; the key stays secret. This pattern is used for storing and transmitting secret data.
Exercise Encrypt and decrypt with AES
In main create val key = SecretKeySpec("0123456789abcdef".toByteArray(), "AES") and val iv = IvParameterSpec("0123456789abcdef".toByteArray()). Take val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"). Encrypt "hello" with ENCRYPT_MODE; then decrypt with DECRYPT_MODE and print println(String(decrypted)).
Show example solution
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import javax.crypto.spec.IvParameterSpec
fun main() {
val key = SecretKeySpec("0123456789abcdef".toByteArray(), "AES")
val iv = IvParameterSpec("0123456789abcdef".toByteArray())
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, key, iv)
val enc = cipher.doFinal("hello".toByteArray())
cipher.init(Cipher.DECRYPT_MODE, key, iv)
val decrypted = cipher.doFinal(enc)
println(String(decrypted))
}
Test yourself
-
Match the AES parts
- Cipher.getInstance
- Cipher object
- SecretKeySpec
- Key
- IvParameterSpec
- IV
- ENCRYPT_MODE
- Encryption mode
-
Which mode is given to Cipher for AES encryption?
- SIGN_MODE
- ENCRYPT_MODE
- HASH_MODE
- VERIFY_MODE
Show answer
ENCRYPT_MODE — ENCRYPT_MODE starts encryption.
-
Complete the Cipher getInstance call
val cipher = Cipher.____("AES/CBC/PKCS5Padding")
Show answer
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
Next lesson: SecureRandom