Skip to content

Instantly share code, notes, and snippets.

@marcobrador
Last active April 18, 2023 14:02
Show Gist options
  • Save marcobrador/9077f89bca7ac5b72a608eb9347b78e5 to your computer and use it in GitHub Desktop.
Save marcobrador/9077f89bca7ac5b72a608eb9347b78e5 to your computer and use it in GitHub Desktop.
const val AAD_LENGTH = 16
const val TAG_LENGTH = 16
class EncryptionOutput(val iv: ByteArray,
val aad: ByteArray,
val tag: ByteArray,
val ciphertext: ByteArray)
fun encrypt(key: SecretKey, message: ByteArray): EncryptionOutput {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, key)
val iv = cipher.iv.copyOf()
val aad = SecureRandom().generateSeed(AAD_LENGTH)
cipher.updateAAD(aad)
val result = cipher.doFinal(message)
val ciphertext = result.copyOfRange(0, result.size - TAG_LENGTH)
val tag = result.copyOfRange(result.size - TAG_LENGTH, result.size)
return EncryptionOutput(iv, aad, tag, ciphertext)
}
fun decrypt(key: SecretKey, iv: ByteArray, aad: ByteArray, tag: ByteArray, ciphertext: ByteArray): ByteArray {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val spec = GCMParameterSpec(TAG_LENGTH * 8, iv)
cipher.init(Cipher.DECRYPT_MODE, key, spec)
cipher.updateAAD(aad)
return cipher.doFinal(ciphertext + tag)
}
@user7
Copy link

user7 commented Jul 25, 2022

Why would you generate random aad just to store it? Aad is supposed to be meaningful data which is then authenticated upon decryption, it should be passed to encrypt as an argument. So the example is kinda misleading or am I missing something?

@user7
Copy link

user7 commented Jul 25, 2022

Also should not GCMParameterSpec appear in encrypt too?

@cyb3rko
Copy link

cyb3rko commented Apr 18, 2023

@user7 You pass the aad to the cipher in line 14, which is then using it for authenticated encryption.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment