-
Notifications
You must be signed in to change notification settings - Fork 5
/
aes_cbc.go
77 lines (69 loc) · 1.64 KB
/
aes_cbc.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
package codec
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"log"
)
func NewAESCBC(keyTypes ...string) *AESCBC {
return &AESCBC{aesKey: newAESKey(keyTypes...)}
}
type AESCBC struct {
*aesKey
}
func (c *AESCBC) genKey(key []byte) []byte {
if c.aesKey == nil {
c.aesKey = newAESKey()
}
return c.GetKey(key)
}
func (c *AESCBC) Encode(rawData, authKey string) string {
crypted := c.EncodeBytes([]byte(rawData), []byte(authKey))
return base64.StdEncoding.EncodeToString(crypted)
}
func (c *AESCBC) Decode(cryptedData, authKey string) string {
crypted, err := base64.StdEncoding.DecodeString(cryptedData)
if err != nil {
log.Println(err)
return ``
}
origData := c.DecodeBytes(crypted, []byte(authKey))
return string(origData)
}
func (c *AESCBC) EncodeBytes(rawData, authKey []byte) []byte {
in := rawData
key := authKey
key = c.genKey(key)
block, err := aes.NewCipher(key)
if err != nil {
log.Println(err)
return nil
}
blockSize := block.BlockSize()
in = PKCS5Padding(in, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
crypted := make([]byte, len(in))
blockMode.CryptBlocks(crypted, in)
return crypted
}
func (c *AESCBC) DecodeBytes(cryptedData, authKey []byte) []byte {
defer func() {
if r := recover(); r != nil {
log.Println(r)
}
}()
in := cryptedData
key := authKey
key = c.genKey(key)
block, err := aes.NewCipher(key)
if err != nil {
log.Println(err)
return nil
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData := make([]byte, len(in))
blockMode.CryptBlocks(origData, in)
origData = PKCS5UnPadding(origData)
return origData
}