Last active
December 8, 2018 17:48
-
-
Save Pagliacii/99a77e70a4b8d9ac2ca6dcc9043ffa66 to your computer and use it in GitHub Desktop.
Caesor Cipher by Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"os" | |
"strings" | |
"unicode" | |
) | |
var ( | |
isEncrypt bool | |
isDecrypt bool | |
rotNum int | |
text string | |
help bool | |
start = int('a') | |
end = int('z') + 1 | |
) | |
func init () { | |
flag.BoolVar(&isEncrypt, "e", false, "Encrypt the plain text") | |
flag.BoolVar(&isDecrypt, "d", false, "Decrypt the encrypted text") | |
flag.IntVar(&rotNum, "n", 13, "Number of places to rotate by") | |
flag.StringVar(&text, "t", "", "Text to encrypt/decrypt") | |
flag.BoolVar(&help, "h", false, "Echo the usage and exit") | |
flag.Parse() | |
flag.Usage = func() { | |
fmt.Fprintln(os.Stderr, ` | |
CaesarCipher - version: 1.0.0 | |
Usage: caesar [-ed] [-n num] [-t text] [-h] | |
Options: | |
`) | |
flag.PrintDefaults() | |
os.Exit(1) | |
} | |
} | |
func encrypt(plainText string, key int) string { | |
encryptedChars := make([]rune, len(plainText)) | |
chars := []rune(plainText) | |
for i, c := range chars { | |
if unicode.IsLetter(c) { | |
encrypted := int(c) + key | |
if encrypted >= end { | |
c = rune(encrypted - end + start) | |
} else { | |
c = rune(encrypted) | |
} | |
} | |
encryptedChars[i] = c | |
} | |
return string(encryptedChars) | |
} | |
func decrypt(cipherText string, key int) string { | |
decryptedChars := make([]rune, len(cipherText)) | |
chars := []rune(cipherText) | |
for i, c := range chars { | |
if unicode.IsLetter(c) { | |
decrypted := int(c) - key | |
if decrypted < start { | |
c = rune(end - (start - decrypted)) | |
} else { | |
c = rune(decrypted) | |
} | |
} | |
decryptedChars[i] = c | |
} | |
return string(decryptedChars) | |
} | |
func main() { | |
if help { | |
flag.Usage() | |
} | |
if (isEncrypt && isDecrypt) || !(isEncrypt || isDecrypt) { | |
fmt.Println("Please specify either encryption mode (-e) or decryption mode (-d).") | |
flag.Usage() | |
} | |
if len(text) == 0 { | |
if isEncrypt { | |
fmt.Println("Please enter the text to be encrypted") | |
} else { | |
fmt.Println("Please enter the text to be decrypted") | |
} | |
flag.Usage() | |
} | |
text = strings.ToLower(strings.TrimSpace(text)) | |
if isEncrypt { | |
fmt.Printf("Encrypted: %s\n", encrypt(text, rotNum)) | |
} else { | |
fmt.Printf("Decrypted: %s\n", decrypt(text, rotNum)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment