Introduction
The Caesar cipher is a classic encryption technique that shifts letters in a message by a fixed number of positions in the alphabet.
This simple yet powerful method is often used as an introduction to cryptography.
In this project, we will implement the Caesar cipher in Go to perform both encryption and decryption.
Objective
The objective of this project is to create a program that encrypts and decrypts messages using the Caesar cipher.
This project introduces learners to character manipulation, modular arithmetic, and string processing in Go.
Code
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
// Caesar cipher encryption
func encrypt(text string, shift int) string {
shift = shift % 26
result := ""
for _, char := range text {
if char >= 'a' && char <= 'z' {
result += string((char-'a'+rune(shift))%26 + 'a')
} else if char >= 'A' && char <= 'Z' {
result += string((char-'A'+rune(shift))%26 + 'A')
} else {
result += string(char)
}
}
return result
}
// Caesar cipher decryption
func decrypt(text string, shift int) string {
return encrypt(text, 26-shift)
}
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Welcome to the Caesar Cipher Program!")
fmt.Println("Choose an option:")
fmt.Println("1. Encrypt a message")
fmt.Println("2. Decrypt a message")
fmt.Print("Enter your choice (1 or 2): ")
choice, _ := reader.ReadString('\n')
choice = strings.TrimSpace(choice)
if choice != "1" && choice != "2" {
fmt.Println("Invalid choice. Please restart the program.")
return
}
fmt.Print("Enter the text: ")
text, _ := reader.ReadString('\n')
text = strings.TrimSpace(text)
fmt.Print("Enter the shift value: ")
var shift int
fmt.Scanln(&shift)
if choice == "1" {
encryptedText := encrypt(text, shift)
fmt.Printf("Encrypted Text: %s\n", encryptedText)
} else {
decryptedText := decrypt(text, shift)
fmt.Printf("Decrypted Text: %s\n", decryptedText)
}
}
Explanation
The program structure is as follows:
-
Encryption Function: The
encrypt
function takes the text and a shift value as input and applies the Caesar cipher by shifting characters using modular arithmetic. It handles both uppercase and lowercase letters, leaving other characters unchanged. -
Decryption Function: The
decrypt
function reverses the encryption by shifting the text back using26 - shift
. - Main Function: The main function provides a menu-driven interface, allowing users to choose between encryption and decryption. It collects the required inputs (text and shift value) and displays the result.
How to Run the Program
-
Ensure you have Go installed on your system. You can download it from
Go's official website. -
Save the code in a file named
caesar_cipher.go
. - Open a terminal and navigate to the directory containing the file.
-
Run the program with the following command:
go run caesar_cipher.go
- Follow the on-screen instructions to encrypt or decrypt a message using the Caesar cipher.