-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcipher.go
More file actions
90 lines (72 loc) · 1.46 KB
/
Copy pathcipher.go
File metadata and controls
90 lines (72 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
* @Author: tr3e
* @Date: 2019-11-26 20:50:43
* @Last Modified by: tr3e
* @Last Modified time: 2019-11-26 20:56:38
*/
package main
import "errors"
type Cipher interface {
Encrypt([]byte) []byte
Decrypt([]byte) []byte
Copy() Cipher
Reset()
}
var cipherMethod = map[string]func(string) (Cipher, error){
"plain": NewPlainCipher,
"xor": NewXorCipher,
}
func NewCipher(method, password string) (Cipher, error) {
cipher, ok := cipherMethod[method]
if !ok {
return nil, errors.New("Unsupported cipher method")
}
return cipher(password)
}
type PlainCipher struct {
}
func NewPlainCipher(string) (Cipher, error) {
return &PlainCipher{}, nil
}
func (c *PlainCipher) Encrypt(p []byte) []byte {
return p
}
func (c *PlainCipher) Decrypt(p []byte) []byte {
return p
}
func (c *PlainCipher) Copy() Cipher {
return c
}
func (c *PlainCipher) Reset() {
}
type XorCipher struct {
encInd int
decInd int
secret string
}
func NewXorCipher(secret string) (Cipher, error) {
return &XorCipher{secret: secret}, nil
}
func (c *XorCipher) Encrypt(p []byte) []byte {
for i := 0; i < len(p); i++ {
c.encInd %= len(c.secret)
p[i] ^= c.secret[c.encInd]
c.encInd++
}
return p
}
func (c *XorCipher) Decrypt(p []byte) []byte {
for i := 0; i < len(p); i++ {
c.decInd %= len(c.secret)
p[i] ^= c.secret[c.decInd]
c.decInd++
}
return p
}
func (c *XorCipher) Copy() Cipher {
return &XorCipher{secret: c.secret}
}
func (c *XorCipher) Reset() {
c.encInd = 0
c.decInd = 0
}