-
Notifications
You must be signed in to change notification settings - Fork 0
/
cipher.go
106 lines (88 loc) 路 1.81 KB
/
cipher.go
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package geheim
import (
"crypto/aes"
"crypto/cipher"
"io"
"golang.org/x/crypto/chacha20"
)
type Cipher int
const (
AES_256 Cipher = 1 + iota
ChaCha20
)
var CipherNames = map[Cipher]string{
AES_256: "AES-256",
ChaCha20: "ChaCha20",
}
var nonceSizes = map[Cipher]int{
AES_256: aes.BlockSize,
ChaCha20: chacha20.NonceSize,
}
var keySizesCipher = map[Cipher]int{
AES_256: 32,
ChaCha20: chacha20.KeySize,
}
var ciphers = [...]Cipher{
AES_256,
ChaCha20,
}
var CipherString = getOptionString(ciphers[:], CipherNames)
type Mode int
const (
CTR Mode = 1 + iota
CFB
OFB
)
var ModeNames = map[Mode]string{
CTR: "CTR",
CFB: "CFB",
OFB: "OFB",
}
var modes = [...]Mode{
CTR,
CFB,
OFB,
}
var ModeString = getOptionString(modes[:], ModeNames)
func getStreamMode(mode Mode, decrypt bool) (StreamMode, error) {
switch mode {
case CTR:
return cipher.NewCTR, nil
case CFB:
if decrypt {
return cipher.NewCFBDecrypter, nil
} else {
return cipher.NewCFBEncrypter, nil
}
case OFB:
return cipher.NewOFB, nil
}
return nil, ErrMode
}
func newCipherStream(cipher Cipher, mode Mode, decrypt bool, key, nonce []byte) (cipher.Stream, error) {
if err := checkBytesSize(nonceSizes, cipher, nonce, "nonce"); err != nil {
return nil, err
}
switch cipher {
case AES_256:
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
sm, err := getStreamMode(mode, decrypt)
if err != nil {
return nil, err
}
return sm(block, nonce), nil
case ChaCha20:
stream, err := chacha20.NewUnauthenticatedCipher(key, nonce)
return stream, err
}
return nil, ErrCipher
}
func newStreamReader(stream cipher.Stream, r io.Reader) io.Reader {
return &cipher.StreamReader{S: stream, R: r}
}
func newStreamWriter(stream cipher.Stream, w io.Writer) io.Writer {
return &cipher.StreamWriter{S: stream, W: w}
}