From 1b1945779d520e29f6e8f550fb55b937da31e774 Mon Sep 17 00:00:00 2001 From: Florian Hoss Date: Mon, 30 May 2022 12:50:59 +0200 Subject: [PATCH] encrypting works --- Lab04/code/part01-encrypt/main.go | 72 ++++++++++++++++++++++++++++++- 1 file changed, 71 insertions(+), 1 deletion(-) diff --git a/Lab04/code/part01-encrypt/main.go b/Lab04/code/part01-encrypt/main.go index f3ae387..04f162b 100644 --- a/Lab04/code/part01-encrypt/main.go +++ b/Lab04/code/part01-encrypt/main.go @@ -1,7 +1,77 @@ package main import ( + "fmt" + "log" + "regexp" + "strings" + "unicode" ) -func main() { +const lettersInTheAlphabet = 26 +const startUpperCase = 65 +const endUpperCase = 65 + lettersInTheAlphabet +const startLowerCase = 97 +const endLowerCase = 97 + lettersInTheAlphabet + +var key string + +type keyLetter struct { + upperCase string + position int32 +} + +func getKeyWord() { + var input string + fmt.Println("Please enter a key word:") + _, err := fmt.Scanln(&input) + if err != nil { + log.Fatalln(err) + } + reg, err := regexp.Compile("[^a-zA-Z]+") + if err != nil { + log.Fatalln(err) + } + processedString := reg.ReplaceAllString(input, "") + key = strings.ToUpper(processedString) +} + +func initKeyWord() []keyLetter { + var keyWord []keyLetter + for _, letter := range key { + keyWord = append(keyWord, keyLetter{ + upperCase: string(letter), + position: letter - 'A', + }) + } + fmt.Println(keyWord) + return keyWord +} + +func encryptMessage(keyWord []keyLetter, message string) string { + encrypted := "" + index := 0 + for _, letter := range message { + if letter == 32 { + encrypted += " " + } else { + keyWordIndex := index % len(keyWord) + newLetter := letter + keyWord[keyWordIndex].position + if (unicode.IsLower(letter) && newLetter >= endLowerCase) || + (unicode.IsUpper(letter) && newLetter >= endUpperCase) { + newLetter -= lettersInTheAlphabet + } + encrypted += string(newLetter) + index += 1 + } + } + return encrypted +} + +func main() { + message := "Make It Happen" + fmt.Println(message) + getKeyWord() + keyWord := initKeyWord() + fmt.Println(encryptMessage(keyWord, message)) }