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/content/part1/encrypt/main.go

91 lines
1.9 KiB
Go
Raw Permalink Normal View History

2022-05-30 11:52:30 +02:00
package main
import (
2022-05-30 13:24:48 +02:00
"flag"
2022-05-30 12:50:59 +02:00
"log"
2022-05-30 13:24:48 +02:00
"os"
2022-05-30 12:50:59 +02:00
"regexp"
"strings"
"unicode"
2022-05-30 11:52:30 +02:00
)
2022-06-08 16:26:04 +02:00
const lettersInTheAlphabet = 'Z' - 'A' + 1
2022-05-30 12:50:59 +02:00
type keyLetter struct {
upperCase string
position int32
}
2022-05-30 13:24:48 +02:00
func parseArguments() (string, string) {
var inputKey string
var inputFile string
flag.StringVar(&inputKey, "k", "", "Specify key word.")
flag.StringVar(&inputFile, "f", "", "Specify file to encrypt.")
flag.Parse()
return inputKey, inputFile
}
func readFile(relativePath string) string {
2022-11-14 18:29:26 +01:00
content, err := os.ReadFile(relativePath)
2022-05-30 13:24:48 +02:00
if err != nil {
log.Fatalln(err)
}
return string(content)
}
func writeFile(relativePath string, message string) {
file, err := os.Create(relativePath)
2022-05-30 12:50:59 +02:00
if err != nil {
log.Fatalln(err)
}
2022-05-30 13:24:48 +02:00
defer file.Close()
file.WriteString(message)
}
func validateKeyWord(inputKey string) string {
2022-05-30 12:50:59 +02:00
reg, err := regexp.Compile("[^a-zA-Z]+")
if err != nil {
log.Fatalln(err)
}
2022-05-30 13:24:48 +02:00
processedString := reg.ReplaceAllString(inputKey, "")
return strings.ToUpper(processedString)
2022-05-30 12:50:59 +02:00
}
2022-05-30 13:24:48 +02:00
func initKeyWord(key string) []keyLetter {
2022-05-30 12:50:59 +02:00
var keyWord []keyLetter
for _, letter := range key {
keyWord = append(keyWord, keyLetter{
upperCase: string(letter),
position: letter - 'A',
})
}
return keyWord
}
func encryptMessage(keyWord []keyLetter, message string) string {
encrypted := ""
index := 0
for _, letter := range message {
2022-05-30 13:24:48 +02:00
if !unicode.IsLetter(letter) {
encrypted += string(letter)
2022-05-30 12:50:59 +02:00
} else {
keyWordIndex := index % len(keyWord)
newLetter := letter + keyWord[keyWordIndex].position
2022-06-08 16:26:04 +02:00
if (unicode.IsLower(letter) && newLetter > 'z') ||
(unicode.IsUpper(letter) && newLetter > 'Z') {
2022-05-30 12:50:59 +02:00
newLetter -= lettersInTheAlphabet
}
encrypted += string(newLetter)
index += 1
}
}
return encrypted
}
2022-05-30 11:52:30 +02:00
func main() {
2022-05-30 13:24:48 +02:00
inputKey, inputFile := parseArguments()
message := readFile(inputFile)
keyWord := initKeyWord(validateKeyWord(inputKey))
writeFile("output.txt", encryptMessage(keyWord, message))
2022-05-30 11:52:30 +02:00
}