-
Notifications
You must be signed in to change notification settings - Fork 0
/
aes.go
59 lines (46 loc) · 1.16 KB
/
aes.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
package rice
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"io"
)
func AESEncrypt(keyString, plainString string) (string, error) {
key, err := hex.DecodeString(keyString)
if err != nil {
return "", err
}
plaintext := []byte(plainString)
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
return hex.EncodeToString(ciphertext), nil
}
func AESDecrypt(keyString, cipherString string) (string, error) {
key, err := hex.DecodeString(keyString)
if err != nil {
return "", err
}
ciphertext, err := hex.DecodeString(cipherString)
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
iv := ciphertext[:aes.BlockSize]
plaintext2 := make([]byte, len(ciphertext[aes.BlockSize:]))
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:])
return string(plaintext2), nil
}