How Do You Implement a Caesar Cipher in Kotlin?

Table of Contents

If you’ve ever wondered how those secret codes from ancient times worked, you’re in for a treat! The Caesar Cipher is one of the simplest and oldest encryption techniques, widely used by Julius Caesar to protect military communications. 

In this blog post, you’ll discover how to create a Caesar Cipher in Kotlin

What Is a Caesar Cipher?

A Caesar Cipher is a type of substitution cipher. It replaces each letter in the plaintext with another letter a fixed number of positions down the alphabet. For example, with a shift of 3, A becomes D, B becomes E, and so on.

Let’s learn how to build a Caesar Cipher in Kotlin together!

Why Use Kotlin for Caesar Cipher?

Kotlin is a concise, safe, and expressive language that’s perfect for learning cryptography basics. It also runs seamlessly on Android and serves well for quick algorithm prototyping.

Implementing Caesar Cipher in Kotlin

Let’s jump right into coding! First, we will create a function that encrypts (encodes) text using the Caesar Cipher method.

1. Caesar Cipher Encryption

Kotlin
fun caesarCipherEncrypt(text: String, shift: Int): String {
    val result = StringBuilder()

    for (char in text) {
        when {
            char.isUpperCase() -> {
                // Encrypt uppercase letters
                val offset = 'A'.toInt()
                val encrypted = ((char.code - offset + shift) % 26 + offset).toChar()
                result.append(encrypted)
            }
            char.isLowerCase() -> {
                // Encrypt lowercase letters
                val offset = 'a'.toInt()
                val encrypted = ((char.code - offset + shift) % 26 + offset).toChar()
                result.append(encrypted)
            }
            else -> result.append(char) // Non-letter characters stay the same
        }
    }

    return result.toString()
}

How It Works

  • Looping Through Text: The code checks every character in the string.
  • Uppercase Letters: For capital letters, it adjusts using the ‘A’ character as a baseline, shifts by the specified amount, and wraps around with % 26 so Z doesn’t go past A.
  • Lowercase Letters: The process is similar, but with ‘a’ as the baseline.
  • Other Characters: Spaces, numbers, or punctuation stay unchanged, so only the message itself is encrypted.

2. Caesar Cipher Decryption

Decrypting is just encrypting with the negative shift!

fun caesarCipherDecrypt(cipherText: String, shift: Int): String {
// Decrypt by shifting in the opposite direction
return caesarCipherEncrypt(cipherText, 26 - (shift % 26))
}
  • Reverse the Shift: Pass the opposite shift to the same function, so letters slide back to their original form.

Let’s see how you can use your Caesar Cipher in Kotlin:

Kotlin
fun main() {
    val originalText = "Hello, Kotlin!"
    val shift = 3

    val encrypted = caesarCipherEncrypt(originalText, shift)
    println("Encrypted: $encrypted") // Output: Khoor, Nrwolq!

    val decrypted = caesarCipherDecrypt(encrypted, shift)
    println("Decrypted: $decrypted") // Output: Hello, Kotlin!
}

This example shows you how to encrypt and decrypt a message easily, keeping spaces and punctuation intact.

Tips for Using Caesar Cipher in Kotlin

  • Pick a Secure Shift: For fun, any shift will work. But remember, Caesar Cipher isn’t strong enough for modern security.
  • Kotlin’s Unicode Support: This method works for A-Z and a-z. If your app will use accented or non-English letters, you might want to enhance the code.
  • Kotlin Extensions: For advanced users, consider extension functions for even cleaner code.

Conclusion

Building a Caesar Cipher in Kotlin is an engaging way to practice your algorithm skills and learn about classic ciphers. With just a few lines of Kotlin, you can encrypt and decrypt your own secret messages — all in a safe, fun, and beginner-friendly way. Perfect for learning, personal projects, or adding a playful feature to your Android app!

Skill Up: Software & AI Updates!

Receive our latest insights and updates directly to your inbox

Related Posts

error: Content is protected !!