diff options
| author | Xe Iaso <me@xeiaso.net> | 2023-08-11 19:46:58 -0400 |
|---|---|---|
| committer | Xe Iaso <me@xeiaso.net> | 2023-08-11 19:46:58 -0400 |
| commit | e50eae921dc8189f8ea34636a77d61897898f019 (patch) | |
| tree | 986513ffa0907bdee4223d1c7a8b84904efc0e58 /conferences | |
| parent | c822591c5a46ad9e8f13d14ac96d2e9d26e7c828 (diff) | |
| download | x-e50eae921dc8189f8ea34636a77d61897898f019.tar.xz x-e50eae921dc8189f8ea34636a77d61897898f019.zip | |
conferences/dc31: add crypto-privacy village puzzle code
Signed-off-by: Xe Iaso <me@xeiaso.net>
Diffstat (limited to 'conferences')
| -rw-r--r-- | conferences/dc31/crypto-privacy/vigenere/main.go | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/conferences/dc31/crypto-privacy/vigenere/main.go b/conferences/dc31/crypto-privacy/vigenere/main.go new file mode 100644 index 0000000..448303b --- /dev/null +++ b/conferences/dc31/crypto-privacy/vigenere/main.go @@ -0,0 +1,69 @@ +package main + +import ( + "flag" + "fmt" + "os" + "strings" + + "within.website/x/internal" +) + +func main() { + internal.HandleStartup() + + if flag.NArg() != 3 { + fmt.Fprintln(os.Stderr, "usage: go run . <encrypt> <plaintext> <key>") + fmt.Fprintln(os.Stderr, "usage: go run . <decrypt> <ciphertext> <key>") + os.Exit(2) + } + + action := flag.Arg(0) + plaintext := flag.Arg(1) + key := flag.Arg(2) + + switch action { + case "encrypt": + fmt.Println(Encrypt(key, plaintext)) + case "decrypt": + fmt.Println(Decrypt(key, plaintext)) + default: + fmt.Fprintln(os.Stderr, "usage: go run . <encrypt> <plaintext> <key>") + fmt.Fprintln(os.Stderr, "usage: go run . <decrypt> <ciphertext> <key>") + os.Exit(2) + } +} + +func ReplicateKey(key string, plaintextLen int) string { + return strings.Repeat(key, plaintextLen/len(key)+1)[:plaintextLen] +} + +func Encrypt(keyRaw, plaintext string) string { + keyRaw = ReplicateKey(keyRaw, len(plaintext)) + plaintextDecoded := make([]int, len(plaintext)) + key := make([]int, len(plaintext)) + encoded := make([]byte, len(plaintext)) + + for i := range plaintext { + plaintextDecoded[i] = int(plaintext[i] - 'A') + key[i] = int(keyRaw[i] - 'A') + encoded[i] = byte(((plaintextDecoded[i] + key[i]) % 26) + 'A') + } + + return string(encoded) +} + +func Decrypt(keyRaw, ciphertext string) string { + keyRaw = ReplicateKey(keyRaw, len(ciphertext)) + ciphertextDecoded := make([]int, len(ciphertext)) + key := make([]int, len(ciphertext)) + encoded := make([]byte, len(ciphertext)) + + for i := range ciphertext { + ciphertextDecoded[i] = int(ciphertext[i] - 'A') + key[i] = int(keyRaw[i] - 'A') + encoded[i] = byte((((ciphertextDecoded[i] - key[i]) + 26) % 26) + 'A') + } + + return string(encoded) +} |
