Golang
Golang






Go Programming: Caesar Cipher Implementation

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 using 26 - 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

  1. Ensure you have Go installed on your system. You can download it from
    Go's official website.
  2. Save the code in a file named caesar_cipher.go.
  3. Open a terminal and navigate to the directory containing the file.
  4. Run the program with the following command:

    go run caesar_cipher.go
  5. Follow the on-screen instructions to encrypt or decrypt a message using the Caesar cipher.

Happy Coding! If you have questions, feel free to reach out at support@learnprogramming.com.

Copyright © Learn Programming. All rights reserved.



By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)