-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcipher.go
45 lines (41 loc) · 944 Bytes
/
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
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
)
var (
SECRET_KEY = []byte("3amS^PeyC&@DyKb%WN3Urmja%ghWx$P*")
)
func encrypt(text []byte) ([]byte, error) {
key := SECRET_KEY
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext := make([]byte, aes.BlockSize + len(text))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], text)
return ciphertext, nil
}
func decrypt(text []byte) ([]byte, error) {
key := SECRET_KEY
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(text) < aes.BlockSize {
return nil, errors.New("ciphertext too short")
}
iv := text[:aes.BlockSize]
text = text[aes.BlockSize:]
cfb := cipher.NewCFBDecrypter(block, iv)
cfb.XORKeyStream(text, text)
return text, nil
}