Use Facebook Conceal To Encrypt String To File And Decrypt (Kotlin)

April 13, 2018
Write string to encrypted file and read/decrypt

Setup Facebook Conceal.

Write string to encrypted file.

// String input
val input = "..."
val inputStream = ByteArrayInputStream(input.toByteArray(UTF_8))

// create output file in cache directory
val timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-kkmmss"))
val outputFile = File.createTempFile("backup-${timestamp}", null, context.cacheDir);

// create Facebook Conceal encrypted output stream
val outputStream = App.getCrypto().getCipherOutputStream(
        outputFile.outputStream(),
        Entity.create("backup_key"))

// write input to output stream
inputStream.use { input ->
    outputStream.use { output ->
        input.copyTo(output)
    }
}

Read/decrypt input from encrypted file.

val inputFile = File(...)

// create Facebook Conceal encrypted input stream from inputFile
val inputStream = crypto.getCipherInputStream(
        inputFile.inputStream(),
        Entity.create(KEY_BACKUP))


// create output stream to read string
val outputStream = ByteArrayOutputStream()

// write input to output stream
inputStream.use { input ->
    outputStream.use { output ->
        input.copyTo(output)
    }
}

// convert ByteArrayOutputStream to string
val output = String(outputStream.toByteArray(), Charsets.UTF_8)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.