Skip to main content

How to encrypt or decrypt a string in Kotlin

How to encrypt or decrypt a string in Kotlin.

Here's a detailed step-by-step tutorial on how to encrypt or decrypt a string in Kotlin.

Introduction

Encryption is the process of converting plain text into cipher text, making it unreadable to unauthorized users. Decryption is the reverse process of converting cipher text back into plain text. In Kotlin, there are several options available for encrypting and decrypting strings, including using libraries or implementing algorithms manually.

Using the Java Cryptography Architecture (JCA)

The Java Cryptography Architecture (JCA) provides a set of classes and interfaces for cryptographic operations. Kotlin can leverage these classes to encrypt and decrypt strings.

Step 1: Add the JCA dependency

To use the JCA for encryption and decryption, you need to include the javax.crypto package in your project. Add the following dependency to your build.gradle file:

dependencies {
implementation 'javax.crypto:jce:1.2.1'
}

Step 2: Encrypt a string

To encrypt a string using the JCA, follow these steps:

  1. Create an instance of the Cipher class:

    val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")

    Here, AES is the encryption algorithm, CBC is the mode of operation, and PKCS5Padding is the padding scheme. You can choose different algorithms, modes, and padding schemes based on your requirements.

  2. Generate a secret key for encryption:

    val secretKey = SecretKeySpec(keyByteArray, "AES")

    Replace keyByteArray with the actual byte array representing your secret key. You can use ByteArray or String to represent the key.

  3. Initialize the cipher in encryption mode with the secret key:

    cipher.init(Cipher.ENCRYPT_MODE, secretKey)
  4. Encrypt the string:

    val encryptedBytes = cipher.doFinal(plainText.toByteArray())

    Replace plainText with the actual string you want to encrypt.

  5. Convert the encrypted bytes to a Base64-encoded string for easy transmission or storage:

    val encryptedString = Base64.getEncoder().encodeToString(encryptedBytes)

Step 3: Decrypt a string

To decrypt a string using the JCA, follow these steps:

  1. Create an instance of the Cipher class:

    val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")

    Use the same algorithm, mode, and padding scheme as used for encryption.

  2. Generate a secret key for decryption:

    val secretKey = SecretKeySpec(keyByteArray, "AES")

    Use the same key as used for encryption.

  3. Initialize the cipher in decryption mode with the secret key:

    cipher.init(Cipher.DECRYPT_MODE, secretKey)
  4. Convert the Base64-encoded string back to encrypted bytes:

    val encryptedBytes = Base64.getDecoder().decode(encryptedString)
  5. Decrypt the bytes:

    val decryptedBytes = cipher.doFinal(encryptedBytes)
  6. Convert the decrypted bytes back to the original plain text:

    val decryptedString = decryptedBytes.toString(Charsets.UTF_8)

Using External Libraries

Apart from the JCA, there are also several external libraries available for encryption and decryption in Kotlin. One popular library is Bouncy Castle.

Step 1: Add the Bouncy Castle dependency

To use Bouncy Castle for encryption and decryption, you need to include the library in your project. Add the following dependency to your build.gradle file:

dependencies {
implementation 'org.bouncycastle:bcprov-jdk15on:1.68'
}

Step 2: Encrypt a string

To encrypt a string using Bouncy Castle, follow these steps:

  1. Create an instance of the Cipher class:

    val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC")

    Here, AES is the encryption algorithm, CBC is the mode of operation, and PKCS7Padding is the padding scheme.

  2. Generate a secret key for encryption:

    val secretKey = SecretKeySpec(keyByteArray, "AES")

    Replace keyByteArray with the actual byte array representing your secret key.

  3. Initialize the cipher in encryption mode with the secret key:

    cipher.init(Cipher.ENCRYPT_MODE, secretKey)
  4. Encrypt the string:

    val encryptedBytes = cipher.doFinal(plainText.toByteArray())
  5. Convert the encrypted bytes to a Base64-encoded string for easy transmission or storage:

    val encryptedString = Base64.getEncoder().encodeToString(encryptedBytes)

Step 3: Decrypt a string

To decrypt a string using Bouncy Castle, follow these steps:

  1. Create an instance of the Cipher class:

    val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC")

    Use the same algorithm, mode, and padding scheme as used for encryption.

  2. Generate a secret key for decryption:

    val secretKey = SecretKeySpec(keyByteArray, "AES")

    Use the same key as used for encryption.

  3. Initialize the cipher in decryption mode with the secret key:

    cipher.init(Cipher.DECRYPT_MODE, secretKey)
  4. Convert the Base64-encoded string back to encrypted bytes:

    val encryptedBytes = Base64.getDecoder().decode(encryptedString)
  5. Decrypt the bytes:

    val decryptedBytes = cipher.doFinal(encryptedBytes)
  6. Convert the decrypted bytes back to the original plain text:

    val decryptedString = decryptedBytes.toString(Charsets.UTF_8)

Conclusion

In this tutorial, you learned how to encrypt and decrypt a string in Kotlin using the Java Cryptography Architecture (JCA) and the Bouncy Castle library. Encryption and decryption are essential techniques for securing sensitive information and ensuring data privacy.