-
Notifications
You must be signed in to change notification settings - Fork 5
/
aes_ecb.go
76 lines (67 loc) · 1.55 KB
/
aes_ecb.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
package codec
import (
"crypto/aes"
"encoding/base64"
"log"
)
func NewAESECB(keyTypes ...string) *AESECB {
return &AESECB{aesKey: newAESKey(keyTypes...)}
}
type AESECB struct {
*aesKey
}
func (c *AESECB) genKey(key []byte) []byte {
if c.aesKey == nil {
c.aesKey = newAESKey()
}
return c.GetKey(key)
}
func (c *AESECB) Encode(rawData, authKey string) string {
crypted := c.EncodeBytes([]byte(rawData), []byte(authKey))
return base64.StdEncoding.EncodeToString(crypted)
}
func (c *AESECB) 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 *AESECB) 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 := NewECBEncrypter(block)
crypted := make([]byte, len(in))
blockMode.CryptBlocks(crypted, in)
return crypted
}
func (c *AESECB) 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
}
blockMode := NewECBDecrypter(block)
origData := make([]byte, len(in))
blockMode.CryptBlocks(origData, in)
origData = PKCS5UnPadding(origData)
return origData
}