Sling Academy
Home/Kotlin/Encrypting and Decrypting Files in Kotlin

Encrypting and Decrypting Files in Kotlin

Last updated: November 30, 2024

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.

Next Article: Using Kotlin Coroutines for Asynchronous File I/O

Previous Article: Reading and Writing XML Files in Kotlin

Series: Kotlin - File & OS

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin