Files
superherohub/pkg/deesee/codec.go

76 lines
2.1 KiB
Go

// Package deesee contains functions for encrypting and decrypting text.
//
// Important:
// - The encryption is not secure at all, it's just a simple substitution cipher.
// - Only the English language is supported.
//
// Ideas:
// - write an encoder and construct like NewEncoder(key).Encode(any), but this is not required at this stage of the project.
// - improve deesee-encoder to work with annotations, something like `deesee:"encode"` to prevent encoding for not authorized properties
package deesee
import "strings"
const (
a = 97 // ASCII code for a
z = 122 // ASCII code for z
)
// Encrypt text and returns an encrypted using the "DeeSee Chiffre" encryption.
func Encrypt(text string, n int) string {
return chiffre(text, n)
}
// Decrypt text and returns a decrypted using the "DeeSee Chiffre" encryption.
func Decrypt(text string, n int) string {
return chiffre(text, -n)
}
// chiffre function takes a string and a key as input and returns the DeeSee encoded string
func chiffre(text string, key int) string {
var (
output strings.Builder // String builder to store the encoded string
ascii int // ASCII value of the current character
)
//
// Convert the text string to lowercase
text = strings.ToLower(text)
// Let the key be in the range of letters
key %= z - a - 1
// Iterate through each character in the text string
for _, char := range text {
// Convert the character to its ASCII value
ascii = int(char)
// Encode only if character is a letter
if isLetter(ascii) {
// Shift the character by the key
ascii += key
// Which direction are we shifting?
if key > 0 {
// If the character is now out of bounds
if ascii > z {
ascii = a + key - 2
}
} else {
// If the character is now out of bounds
if ascii < a {
ascii = z + key + 2
}
}
}
// Append the encoded character to the output string
output.WriteRune(rune(ascii))
}
return output.String()
}
// isLetter returns true if the given character is inside of ASCII letter diapason.
func isLetter(char int) bool {
return char >= a && char <= z
}