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

96 lines
2.1 KiB
Go
Raw Normal View History

2022-05-30 11:52:30 +02:00
package main
import (
2022-05-30 13:24:48 +02:00
"flag"
"io/ioutil"
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-05-30 12:50:59 +02:00
const lettersInTheAlphabet = 26
const startUpperCase = 65
2022-05-30 13:24:48 +02:00
const endUpperCase = startUpperCase + lettersInTheAlphabet
2022-05-30 12:50:59 +02:00
const startLowerCase = 97
2022-05-30 13:24:48 +02:00
const endLowerCase = startLowerCase + lettersInTheAlphabet
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 {
content, err := ioutil.ReadFile(relativePath)
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
if (unicode.IsLower(letter) && newLetter >= endLowerCase) ||
(unicode.IsUpper(letter) && newLetter >= endUpperCase) {
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
}