This repository has been archived on 2024-10-30. You can view files and clone it, but cannot push or open issues or pull requests.
swb6-it-sec/Lab04/code/part01-encrypt/main.go
2022-05-30 12:50:59 +02:00

77 lines
1.5 KiB
Go

package main
import (
"fmt"
"log"
"regexp"
"strings"
"unicode"
)
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))
}