Skip to content

Instantly share code, notes, and snippets.

View marcobrador's full-sized avatar

Marc Obrador marcobrador

  • Build38
  • Barcelona, Spain
View GitHub Profile
fun generateAesKey(): SecretKey {
val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
val kgps = KeyGenParameterSpec.Builder("my_aes_key", KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
// This is required to be able to provide the IV ourselves
.setRandomizedEncryptionRequired(false)
.build()
keyGenerator.init(kgps)
return keyGenerator.generateKey()
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)
const val AAD_LENGTH = 16
const val TAG_LENGTH = 16
class EncryptionOutput(val iv: ByteArray,
val aad: ByteArray,
val tag: ByteArray,
val ciphertext: ByteArray)
fun encrypt(key: SecretKey, message: ByteArray): EncryptionOutput {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
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()
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)
}