Skip to content

Instantly share code, notes, and snippets.

@LethalMaus
Created March 10, 2026 19:55
Show Gist options
  • Select an option

  • Save LethalMaus/b95b9c9a2fb1f1f9a25a24397434b565 to your computer and use it in GitHub Desktop.

Select an option

Save LethalMaus/b95b9c9a2fb1f1f9a25a24397434b565 to your computer and use it in GitHub Desktop.
Secure AES-GCM encryption with random IV and explicit tag split
override fun encryptAesGcm(plaintext: ByteArray, aad: ByteArray?): CryptoHelper.AesGcmResult {
val key = currentKey()
val iv = ByteArray(12)
random.nextBytes(iv)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val spec = GCMParameterSpec(128, iv)
cipher.init(Cipher.ENCRYPT_MODE, key, spec)
if (aad != null) cipher.updateAAD(aad)
val out = cipher.doFinal(plaintext)
// Split cipherText and tag (last 16 bytes) for teaching clarity
val tagLen = 16
val ct = out.copyOfRange(0, out.size - tagLen)
val tag = out.copyOfRange(out.size - tagLen, out.size)
return CryptoHelper.AesGcmResult(iv, ct, tag)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment