In this tutorial, we'll learn how to encrypt and decrypt files using Kotlin. Encrypting files ensures the security and privacy of data, preventing unauthorized access. We'll cover the steps needed to implement file encryption using the Cipher class in the javax.crypto package.
Prerequisites
- Ensure that you have JDK 1.8 or above installed on your system.
- Basic knowledge of Kotlin programming language.
Setup
To use encryption and decryption in Kotlin, add the following import statements at the top of your Kotlin file:
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import java.io.File
Generating a Secret Key
A Secret Key is essential for both encrypting and decrypting data. Here's how you can generate a secret key for AES encryption:
fun generateSecretKey(): SecretKey {
val keyGen = KeyGenerator.getInstance("AES")
keyGen.init(256) // specify key size
return keyGen.generateKey()
}
Encrypting a File
With the secret key ready, you can encrypt a file using the following function:
fun encryptFile(secretKey: SecretKey, inputFilePath: String, outputFilePath: String) {
val cipher = Cipher.getInstance("AES")
cipher.init(Cipher.ENCRYPT_MODE, secretKey)
val inputFile = File(inputFilePath).readBytes()
val outputBytes = cipher.doFinal(inputFile)
File(outputFilePath).writeBytes(outputBytes)
println("File encrypted successfully.")
}
Decrypting a File
To decrypt a file, use the same secret key and reverse the encryption process as shown below:
fun decryptFile(secretKey: SecretKey, inputFilePath: String, outputFilePath: String) {
val cipher = Cipher.getInstance("AES")
cipher.init(Cipher.DECRYPT_MODE, secretKey)
val inputFile = File(inputFilePath).readBytes()
val outputBytes = cipher.doFinal(inputFile)
File(outputFilePath).writeBytes(outputBytes)
println("File decrypted successfully.")
}
Full Code Example
Here's a complete example demonstrating both the encryption and decryption processes:
fun main() {
val secretKey = generateSecretKey()
val inputFilePath = "path/to/your/inputfile.txt"
val encryptedFilePath = "path/to/your/encryptedfile.enc"
val decryptedFilePath = "path/to/your/decryptedfile.txt"
// Encrypt the file
encryptFile(secretKey, inputFilePath, encryptedFilePath)
// Decrypt the file
decryptFile(secretKey, encryptedFilePath, decryptedFilePath)
}
Make sure to change the paths to the files you want to use. This example demonstrates how to use the AES encryption algorithm to secure files in Kotlin.