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

Write string to encrypted file and read/decrypt

Setup Facebook Conceal.

Write string to encrypted file.

// String inputval input = "..."val inputStream = ByteArrayInputStream(input.toByteArray(UTF_8))// create output file in cache directoryval timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-kkmmss"))val outputFile = File.createTempFile("backup-${timestamp}", null, context.cacheDir);// create Facebook Conceal encrypted output streamval outputStream = App.getCrypto().getCipherOutputStream(        outputFile.outputStream(),        Entity.create("backup_key"))// write input to output streaminputStream.use { input ->    outputStream.use { output ->        input.copyTo(output)    }}

Read/decrypt input from encrypted file.

val inputFile = File(...)// create Facebook Conceal encrypted input stream from inputFileval inputStream = crypto.getCipherInputStream(        inputFile.inputStream(),        Entity.create(KEY_BACKUP))// create output stream to read stringval outputStream = ByteArrayOutputStream()// write input to output streaminputStream.use { input ->    outputStream.use { output ->        input.copyTo(output)    }}// convert ByteArrayOutputStream to stringval output = String(outputStream.toByteArray(), Charsets.UTF_8)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.