Last active
January 27, 2021 06:45
-
-
Save marcobrador/929f3f688e4888eacb4cf88e2269882a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const val TAG_LENGTH = 16 | |
class EncryptionOutput(val iv: 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 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, tag, ciphertext) | |
} | |
fun decrypt(key: SecretKey, iv: 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) | |
return cipher.doFinal(ciphertext + tag) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment