Skip to content

Instantly share code, notes, and snippets.

@marcobrador
Last active March 27, 2020 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcobrador/75b7164c7315e25db163bc04b9b9dfc2 to your computer and use it in GitHub Desktop.
Save marcobrador/75b7164c7315e25db163bc04b9b9dfc2 to your computer and use it in GitHub Desktop.
const val TAG_LENGTH = 16
class EncryptionOutput(val tag: ByteArray,
val ciphertext: ByteArray)
fun encrypt(key: SecretKey, iv: ByteArray, aad: ByteArray, message: ByteArray): EncryptionOutput {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val spec = GCMParameterSpec(TAG_LENGTH * 8, iv)
cipher.init(Cipher.ENCRYPT_MODE, key, spec)
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(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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment