Skip to content

Commit 55043d1

Browse files
committed
Merge remote-tracking branch 'cfvescovo/polybius' into add-tests-for-polybius-cipher
2 parents 20aa579 + a30f367 commit 55043d1

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

ciphers/polybius.go

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package main
2+
3+
import (
4+
"errors"
5+
"strings"
6+
)
7+
8+
type polybius struct {
9+
size int
10+
characters string
11+
key string
12+
}
13+
14+
func newPolybius(key string, size int, chars string) (*polybius, error) {
15+
key = strings.ToUpper(key)
16+
chars = strings.ToUpper(chars)[:size]
17+
if len(chars) != size {
18+
return nil, errors.New("chars must be as long as size")
19+
}
20+
if len(key) != size*size {
21+
return nil, errors.New("key must be as long as the size squared")
22+
}
23+
return &polybius{size, chars, key}, nil
24+
}
25+
26+
func (p *polybius) encrypt(text string) string {
27+
chars := []rune(strings.ToUpper(text))
28+
encryptedText := ""
29+
for _, char := range chars {
30+
encryptedText += p.encipher(char)
31+
}
32+
return encryptedText
33+
}
34+
35+
func (p *polybius) decrypt(text string) string {
36+
chars := []rune(strings.ToUpper(text))
37+
decryptedText := ""
38+
for i := 0; i < len(chars); i += 2 {
39+
decryptedText += p.decipher(chars[i : i+2])
40+
}
41+
return decryptedText
42+
}
43+
44+
func (p *polybius) encipher(char rune) string {
45+
index := strings.IndexRune(p.key, char)
46+
row := index / p.size
47+
col := index % p.size
48+
chars := []rune(p.characters)
49+
return string([]rune{chars[row], chars[col]})
50+
}
51+
52+
func (p *polybius) decipher(chars []rune) string {
53+
if len(chars) != 2 {
54+
panic("decipher takes two chars")
55+
}
56+
row := strings.IndexRune(p.characters, chars[0])
57+
col := strings.IndexRune(p.characters, chars[1])
58+
return string([]rune(p.key)[row*p.size+col])
59+
}

0 commit comments

Comments
 (0)