From 8eba596d6e3a319458d995371a6113ac3302a2da Mon Sep 17 00:00:00 2001 From: Aaron Johnon Date: Mon, 2 Sep 2024 01:21:12 -0500 Subject: [PATCH] Rewrote the encoder to be stronger and simpler --- nsencode.go | 88 ++++++++++++++++++++++++++++++++ nsencoder.go => nsencoder-old.go | 0 2 files changed, 88 insertions(+) create mode 100644 nsencode.go rename nsencoder.go => nsencoder-old.go (100%) diff --git a/nsencode.go b/nsencode.go new file mode 100644 index 0000000..e303af0 --- /dev/null +++ b/nsencode.go @@ -0,0 +1,88 @@ +package main + +import ( + "bufio" + "flag" + "fmt" + "os" + "strings" + "unicode" +) + +// Function to encode characters into their respective number pairs +func encodeChar(char rune) int { + // Define the alphabet and numbers with a leading space + alphabet := " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + + // Find the index of the character + index := strings.IndexRune(alphabet, char) + if index == -1 { + return -1 // Return -1 if character is not found + } + return index +} + +// Function to apply shift and wrap around +func applyShift(value, shift int) int { + shifted := (value + shift) % 37 + if shifted < 0 { + shifted += 37 + } + return shifted +} + +// Function to format the output based on group size +func formatOutput(encoded []int, groupSize int) string { + var output strings.Builder + for _, num := range encoded { + output.WriteString(fmt.Sprintf("%02d", num)) + } + + // Apply grouping + finalOutput := output.String() + if groupSize > 0 { + var groupedOutput strings.Builder + for i := 0; i < len(finalOutput); i += groupSize { + if i+groupSize < len(finalOutput) { + groupedOutput.WriteString(finalOutput[i:i+groupSize] + " ") + } else { + groupedOutput.WriteString(finalOutput[i:]) + } + } + return strings.TrimSpace(groupedOutput.String()) + } + + return finalOutput +} + +func main() { + // Define command-line flags + shift := flag.Int("s", 0, "Shift amount for the cipher") + groupSize := flag.Int("g", 0, "Group size for output formatting") + flag.Parse() + + // Read input from stdin + reader := bufio.NewReader(os.Stdin) + input, _ := reader.ReadString('\n') + input = strings.TrimSpace(input) + + var encoded []int + + // Encode the input string + for _, char := range input { + if !unicode.IsLetter(char) && !unicode.IsDigit(char) && char != ' ' { + continue // Skip characters not in the defined alphabet and numbers + } + encodedValue := encodeChar(unicode.ToUpper(char)) + if encodedValue == -1 { + continue // Skip characters not found in the alphabet string + } + shiftedValue := applyShift(encodedValue, *shift) + encoded = append(encoded, shiftedValue) + } + + // Format the output + formattedOutput := formatOutput(encoded, *groupSize) + fmt.Println(formattedOutput) +} + diff --git a/nsencoder.go b/nsencoder-old.go similarity index 100% rename from nsencoder.go rename to nsencoder-old.go