CodeBlanks Logo Icon CodeBlanks

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.

Practice 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)).

Starter code

Main.kt
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import javax.crypto.spec.IvParameterSpec

// in main create AES key and IV
// encrypt, then decrypt and print the decrypted text

Sample solution

Main.kt
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))
}

Expected output

hello

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the AES parts

Term Meaning
Cipher.getInstance Cipher object
SecretKeySpec Key
IvParameterSpec IV
ENCRYPT_MODE Encryption mode

2 Which mode is given to Cipher for AES encryption?

  • SIGN_MODE
  • ENCRYPT_MODE Correct answer
  • HASH_MODE
  • VERIFY_MODE

Explanation: ENCRYPT_MODE starts encryption.

3 Complete the Cipher getInstance call

Question
val cipher = Cipher.____("AES/CBC/PKCS5Padding")
Answer
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")

Explanation: Cipher.getInstance selects the transformation.

All lessons in Advanced