2

I am getting an exception while decrypting the encrypted file. Exception happening in the decryptFile() method. Line where exception happening is

 while (fileInputStream.read(buffer).also { read = it } != -1) {

Full code below

fun encryptFile(source: File, destination: File, applicationContext: Context) {
    val mainKey = MasterKey.Builder(applicationContext, MasterKey.DEFAULT_MASTER_KEY_ALIAS)
        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
        .build()

    val encryptedFile = EncryptedFile.Builder(
        applicationContext,
        destination,
        mainKey,
        EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
    ).build()

    val fileOutputStream = encryptedFile.openFileOutput()
    val fileInputStream = FileInputStream(source)

    val buffer = ByteArray(1024)
    var read: Int
    while (fileInputStream.read(buffer).also { read = it } != -1) {
        fileOutputStream.write(buffer, 0, read)
    }

    fileInputStream.close()
    fileOutputStream.flush()
    fileOutputStream.close()
    source.delete()
    destination.renameTo(source)
}

fun decryptFile(source: File, destination: File, applicationContext: Context){
    val mainKey = MasterKey.Builder(applicationContext, MasterKey.DEFAULT_MASTER_KEY_ALIAS)
        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
        .build()

    val encryptedFile = EncryptedFile.Builder(
        applicationContext,
        source,
        mainKey,
        EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
    ).build()

    val fileInputStream = encryptedFile.openFileInput()
    val fileOutputStream = FileOutputStream(destination)

    val buffer = ByteArray(1024)
    var read: Int

    while (fileInputStream.read(buffer).also { read = it } != -1) {
        fileOutputStream.write(buffer, 0, read)
    }

    fileInputStream.close()
    fileOutputStream.flush()
    fileOutputStream.close()
    source.delete()
    destination.renameTo(source)
}

I am using the alpha version of the security. Why I am using the alpha version of the security because the stable version is marked as deprecated in the official documentation

implementation("androidx.security:security-crypto:1.1.0-alpha03")
implementation("androidx.security:security-identity-credential:1.0.0-alpha02")
implementation("androidx.security:security-app-authenticator:1.0.0-alpha02")
KIRAN K J
  • 632
  • 5
  • 28
  • 57

0 Answers0