Skip to main content

How to read and write encrypted files in Kotlin

How to read and write encrypted files in Kotlin.

Here's a step-by-step tutorial on how to read and write encrypted files in Kotlin.

Step 1: Import the necessary libraries

To work with encrypted files in Kotlin, you'll need to import the following libraries:

import java.io.*
import javax.crypto.*
import javax.crypto.spec.SecretKeySpec
import java.security.*
import java.util.Base64

Step 2: Generate a secret key

A secret key is required to encrypt and decrypt files. You can generate a secret key using the following function:

fun generateKey(): SecretKey {
val keyGen = KeyGenerator.getInstance("AES")
keyGen.init(128)
return keyGen.generateKey()
}

Step 3: Encrypt a file

To encrypt a file, you need to read the file content and apply the encryption algorithm using the secret key. Here's an example of how to encrypt a file:

fun encryptFile(inputFilePath: String, outputFilePath: String, secretKey: SecretKey) {
val cipher = Cipher.getInstance("AES")
cipher.init(Cipher.ENCRYPT_MODE, secretKey)

val inputFile = File(inputFilePath)
val outputFile = File(outputFilePath)

val inputStream = FileInputStream(inputFile)
val outputStream = FileOutputStream(outputFile)

val inputBytes = ByteArray(inputFile.length().toInt())
inputStream.read(inputBytes)

val outputBytes = cipher.doFinal(inputBytes)

outputStream.write(outputBytes)

inputStream.close()
outputStream.close()
}

Step 4: Decrypt a file

To decrypt a file, you need to read the encrypted file content and apply the decryption algorithm using the secret key. Here's an example of how to decrypt a file:

fun decryptFile(inputFilePath: String, outputFilePath: String, secretKey: SecretKey) {
val cipher = Cipher.getInstance("AES")
cipher.init(Cipher.DECRYPT_MODE, secretKey)

val inputFile = File(inputFilePath)
val outputFile = File(outputFilePath)

val inputStream = FileInputStream(inputFile)
val outputStream = FileOutputStream(outputFile)

val inputBytes = ByteArray(inputFile.length().toInt())
inputStream.read(inputBytes)

val outputBytes = cipher.doFinal(inputBytes)

outputStream.write(outputBytes)

inputStream.close()
outputStream.close()
}

Step 5: Usage example

Here's an example of how to use the encryptFile and decryptFile functions:

fun main() {
val inputFilePath = "input.txt"
val outputFilePath = "output.txt"

// Generate a secret key
val secretKey = generateKey()

// Encrypt the file
encryptFile(inputFilePath, outputFilePath, secretKey)
println("File encrypted successfully!")

// Decrypt the file
decryptFile(outputFilePath, "decrypted.txt", secretKey)
println("File decrypted successfully!")
}

In this example, "input.txt" is the file you want to encrypt, and "output.txt" is the encrypted file. The decrypted file will be saved as "decrypted.txt".

That's it! You now have a step-by-step guide on how to read and write encrypted files in Kotlin. You can use these functions to secure your file contents.