Created
March 10, 2026 19:55
-
-
Save LethalMaus/b95b9c9a2fb1f1f9a25a24397434b565 to your computer and use it in GitHub Desktop.
Secure AES-GCM encryption with random IV and explicit tag split
This file contains hidden or 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
| 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