Search code examples
encryptionkotlintink

Decryption failed after registering AeadConfig more than once?


I'm encrypting some text and trying to decrypt it, however it's failing to decrypt when I am using a different AeadConfig.register() to decrypt than to encrypt. I'm wondering how to resolve this problem because I'll be encrypting on one activity and decrypting in another activity. I've simplified it for the sake of giving an example below.

This works, if I just pass the aead as a parameter, but I'm not sure if that's something I should be doing.

private fun deletableEncrypt() {

    AeadConfig.register()

    val keysetHandle: KeysetHandle = KeysetHandle.generateNew(AeadKeyTemplates.AES128_GCM)
    val aead: Aead = AeadFactory.getPrimitive(keysetHandle)

    val plainText = "Hello world"
    val aad = "masterpassword"

    val cipherText = aead.encrypt(plainText.toByteArray(), aad.toByteArray())

    Log.d(TAG, cipherText.toString())

    dbHelper.insertNewRow("text", cipherText,
        "moreText")
}

private fun deleteableDecrypt() {

    AeadConfig.register()

    val keysetHandle: KeysetHandle = KeysetHandle.generateNew(AeadKeyTemplates.AES128_GCM)
    val aead: Aead = AeadFactory.getPrimitive(keysetHandle)

    val aad = "masterpassword"

    val cipherText = dbHelper.getAllEncrypts()[0]

    val decrypted = aead.decrypt(cipherText, aad.toByteArray())
}

Right now the decryption throws an exception. I think its' caused by the aeadConfig, but I don't know how to register it only once, so once this is solved it won't throw exception anymore.


Solution

  • I actually found the error, I'm generating a new KeySet everytime, when instead I should be storing it. Instructions on how to do that are found here https://github.com/google/tink/blob/master/docs/JAVA-HOWTO.md in the "Storing Keysets" section