Skip to content

Instantly share code, notes, and snippets.

@marcobrador
Last active March 27, 2020 10:30
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/403823c6dc29b806845ce7a1968dc81e to your computer and use it in GitHub Desktop.
Save marcobrador/403823c6dc29b806845ce7a1968dc81e to your computer and use it in GitHub Desktop.
const val TAG_LENGTH = 16
fun encrypt(key: SecretKey, message: ByteArray): Pair<ByteArray, ByteArray> {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, key)
val iv = cipher.iv.copyOf()
val ciphertext = cipher.doFinal(message)
return Pair(iv, ciphertext)
}
fun decrypt(key: SecretKey, iv: ByteArray, message: ByteArray): ByteArray {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val spec = GCMParameterSpec(TAG_LENGTH * 8, iv)
cipher.init(Cipher.DECRYPT_MODE, key, spec)
return cipher.doFinal(message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment