This repository has been archived by the owner on Jun 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcryptor.go
111 lines (98 loc) · 2.6 KB
/
cryptor.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
107
108
109
110
111
package xweb
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"github.com/coscms/xweb/lib/str"
"log"
)
type Cryptor interface {
Encode(rawData, authKey string) string
Decode(cryptedData, authKey string) string
}
type AesCrypto struct {
key map[string][]byte
}
var DefaultCryptor Cryptor = &AesCrypto{key: make(map[string][]byte, 0)}
const (
aesKeyLen = 128
keyLen = aesKeyLen / 8
)
func (c *AesCrypto) aesKey(key []byte) []byte {
if c.key == nil {
c.key = make(map[string][]byte, 0)
}
ckey := string(key)
k, ok := c.key[ckey]
if !ok {
if len(key) == keyLen {
return key
}
k = make([]byte, keyLen)
copy(k, key)
for i := keyLen; i < len(key); {
for j := 0; j < keyLen && i < len(key); j, i = j+1, i+1 {
k[j] ^= key[i]
}
}
c.key[ckey] = k
}
return k
}
func (c *AesCrypto) Encode(rawData, authKey string) string {
in := []byte(rawData)
key := []byte(authKey)
key = c.aesKey(key)
block, err := aes.NewCipher(key)
if err != nil {
log.Println(err)
return ""
}
blockSize := block.BlockSize()
in = PKCS5Padding(in, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
crypted := make([]byte, len(in))
blockMode.CryptBlocks(crypted, in)
return str.Base64Encode(string(crypted))
}
func (c *AesCrypto) Decode(cryptedData, authKey string) string {
cryptedData = str.Base64Decode(cryptedData)
if cryptedData == "" {
return ""
}
in := []byte(cryptedData)
key := []byte(authKey)
key = c.aesKey(key)
block, err := aes.NewCipher(key)
if err != nil {
log.Println(err)
return ""
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData := make([]byte, len(in))
blockMode.CryptBlocks(origData, in)
origData = PKCS5UnPadding(origData)
return string(origData)
}
func ZeroPadding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{0}, padding)
return append(ciphertext, padtext...)
}
func ZeroUnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
// 去掉最后一个字节 unpadding 次
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}