J. R. Swab

Create A Quick and Easy Caesar Cipher

Categories: [Technology]

... a Caesar cipher ... is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence. Wikipedia

I was signing up for a website that teaches the basics of cryptography and instead of a captcha they asked me to decrypt a four words than were encrypted with a Caeser Cipher.

So naturally I work a program to do it for me!

Once you know the byte representation of a few key letters the logic is very simple.

Shifting Forward:

func shiftRight(words string, amount byte) string {
    var output string
    for _, v := range []byte(words) {
        var b byte

        switch v {
        case 32: // Check for spaces
            b = 32
        case 90: // Change "Z" to "A"
            b = 65
        case 122: // Change "z" to "a"
            b = 97
        default:
            b = v + amount
        }

        output = fmt.Sprintf("%s%s", output, string(b))
    }
    return output
}

Shifting Backward

The logic is identical to shifting forward with only a few changes. Such as swapping cases 2 and 3 to look for the A's instead of the Z's. As well as changing the addition to subtraction.

func shiftLeft(words string, amount byte) string {
    var output string
    for _, v := range []byte(words) {
        var b byte

        switch v {
        case 32: // Check for spaces
            b = 32
        case 65: // Change "A" to "Z"
            b = 90
        case 97: // Change "a" to "z"
            b = 122
        default:
            b = v - amount
        }

        output = fmt.Sprintf("%s%s", output, string(b))
    }
    return output
}

Execution:

Running the above functions is as easy as assigning the function to a variable. Then passing in the string you want to encrypt or decrypt with the amount of shifting and printing the output.

func main() {
    word := "J nbef b Dbftbs djqifs"

    decrypted := shiftLeft(word, 1)
    fmt.Println(decrypted)
}

Run it in the playground!