| 51 | } |
| 52 | |
| 53 | func 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 | |
| 83 | func Decrypt(text []rune, keyWord string) ([]rune, error) { |
| 84 | key := getKey(keyWord) |