Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Encryption in Scala

Introduction to Encryption

Encryption is a process that transforms data into a secure format, making it unreadable to unauthorized users. This tutorial will cover how to implement encryption in Scala, focusing on the Java Cryptography Architecture (JCA) which Scala can leverage.

Setting Up Your Scala Environment

Before we start coding, ensure you have Scala and an IDE or text editor installed. You can use sbt (Scala Build Tool) for managing dependencies.

To create a new Scala project, use the following command:

sbt new scala/scala-seed.g8

Basic Encryption and Decryption

We will use the AES (Advanced Encryption Standard) algorithm for encryption and decryption. Here's how to implement it:

First, add the necessary imports:

import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import java.util.Base64

Next, let's create a simple encryption and decryption function:

Here’s the complete code:

object EncryptionExample {
    private val ALGORITHM = "AES"
    
    def encrypt(data: String, secretKey: String): String = {
        val key = new SecretKeySpec(secretKey.getBytes("UTF-8"), ALGORITHM)
        val cipher = Cipher.getInstance(ALGORITHM)
        cipher.init(Cipher.ENCRYPT_MODE, key)
        Base64.getEncoder.encodeToString(cipher.doFinal(data.getBytes("UTF-8")))
    }

    def decrypt(encryptedData: String, secretKey: String): String = {
        val key = new SecretKeySpec(secretKey.getBytes("UTF-8"), ALGORITHM)
        val cipher = Cipher.getInstance(ALGORITHM)
        cipher.init(Cipher.DECRYPT_MODE, key)
        new String(cipher.doFinal(Base64.getDecoder.decode(encryptedData)))
    }

    def main(args: Array[String]): Unit = {
        val secretKey = "1234567890123456" // 16-byte key for AES-128
        val originalData = "Hello, World!"
        val encryptedData = encrypt(originalData, secretKey)
        val decryptedData = decrypt(encryptedData, secretKey)

        println(s"Original: $originalData")
        println(s"Encrypted: $encryptedData")
        println(s"Decrypted: $decryptedData")
    }
}
                    

Running the Example

To run the above code, use the following command in your terminal while in the project directory:

sbt run

The expected output will be:

Original: Hello, World!
Encrypted: 
Decrypted: Hello, World!
                

Conclusion

In this tutorial, we learned the basics of encryption in Scala using the AES algorithm. We covered how to set up a Scala project, implement encryption and decryption, and run the example. Always remember to securely manage your encryption keys to protect sensitive data.