MCPcopy
hub / github.com/TheAlgorithms/Go / Encrypt

Function Encrypt

cipher/transposition/transposition.go:53–81  ·  view source on GitHub ↗
(text []rune, keyWord string)

Source from the content-addressed store, hash-verified

51}
52
53func Encrypt(text []rune, keyWord string) ([]rune, error) {
54 key := getKey(keyWord)
55 keyLength := len(key)
56 textLength := len(text)
57 if keyLength <= 0 {
58 return nil, ErrKeyMissing
59 }
60 if textLength <= 0 {
61 return nil, ErrNoTextToEncrypt
62 }
63 if text[len(text)-1] == placeholder {
64 return nil, fmt.Errorf("%w: cannot encrypt a text, %q, ending with the placeholder char %q", ErrNoTextToEncrypt, text, placeholder)
65 }
66 n := textLength % keyLength
67
68 for i := 0; i < keyLength-n; i++ {
69 text = append(text, placeholder)
70 }
71 textLength = len(text)
72 var result []rune
73 for i := 0; i < textLength; i += keyLength {
74 transposition := make([]rune, keyLength)
75 for j := 0; j < keyLength; j++ {
76 transposition[key[j]-1] = text[i+j]
77 }
78 result = append(result, transposition...)
79 }
80 return result, nil
81}
82
83func Decrypt(text []rune, keyWord string) ([]rune, error) {
84 key := getKey(keyWord)

Callers 4

TestEncryptFunction · 0.70
TestDecryptFunction · 0.70
TestEncryptDecryptFunction · 0.70
FuzzTranspositionFunction · 0.70

Calls 1

getKeyFunction · 0.85

Tested by 4

TestEncryptFunction · 0.56
TestDecryptFunction · 0.56
TestEncryptDecryptFunction · 0.56
FuzzTranspositionFunction · 0.56