Caesar Cipher

The Caesar Cipher is a simply encoding algorithm used during the Roman Empire to hide secret message.

U0705

Code Snippets

package main

import (
    "fmt"
    "os"
)

func cipher(text string, direction int) string {

        shift, offset := rune(3), rune(26)
	runes := []rune(text)

        for index, char := range runes {
		switch direction {
		case -1: // encoding
			if char >= 'a'+shift && char <= 'z' ||
				char >= 'A'+shift && char <= 'Z' {
				char = char - shift
			} else if char >= 'a' && char < 'a'+shift ||
				char >= 'A' && char < 'A'+shift {
				char = char - shift + offset
			}
		case +1: // decoding
			if char >= 'a' && char <= 'z'-shift ||
				char >= 'A' && char <= 'Z'-shift {
				char = char + shift
			} else if char > 'z'-shift && char <= 'z' ||
				char > 'Z'-shift && char <= 'Z' {
				char = char + shift - offset
			}
		}
		runes[index] = char
	}
	return string(runes)
}

func encode(text string) string { return cipher(text, -1) }
func decode(text string) string { return cipher(text, +1) }

func main() {
	sec := os.Args[1]
        fmt.Println("[+] Clear text: " + sec)
	encoded := encode(sec)
	fmt.Println("[+] Encoded: " + encoded)
	decoded := decode(encoded)
	fmt.Println("[+] Decoded: " + decoded)
}

Additional Resources

Subscribe to our Newsletter


The information entered into this form is mandatory. It will be subjected to computer processing. It is processed by computer in order to support our users and readers. The recipients of the data will be : contact@unprotect.it.

According to the Data Protection Act of January 6th, 1978, you have at any time, a right of access to and rectification of all of your personal data. If you wish to exercise this right and gain access to your personal data, please write to Thomas Roccia at contact@unprotect.it.

You may also oppose, for legitimate reasons, the processing of your personal data.