forked from keepole/kiris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto.go
79 lines (70 loc) · 1.83 KB
/
crypto.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
// crypto.go kee > 2019/11/11
package kiris
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"log"
)
// AES 加密
func AESEncrypt(origin, key, mod string) []byte {
originBytes, keyBytes := []byte(origin), []byte(key)
// 分组密钥
block, e := aes.NewCipher(keyBytes)
if e != nil {
log.Fatal(e)
}
// 获取密钥长度
blockSize := block.BlockSize()
// pkcs7
originBytes = PKCS7Padding(originBytes, blockSize)
// 模式
blockMode := cipher.NewCBCEncrypter(block, keyBytes[:blockSize])
// encrypt
cryted := make([]byte, len(originBytes))
blockMode.CryptBlocks(cryted, originBytes)
return cryted
//return Base64Encode(cryted)
}
// AES 解码
func AESDecrypt(cryted []byte, key, mod string) string {
//crytedBytes, keyBytes := Base64Decode(cryted), []byte(key)
keyBytes := []byte(key)
// 分组秘钥
block, e := aes.NewCipher(keyBytes)
if e != nil {
log.Fatal(e)
}
// 获取秘钥块的长度
blockSize := block.BlockSize()
// 加密模式
blockMode := cipher.NewCBCDecrypter(block, keyBytes[:blockSize])
origin := make([]byte, len(cryted))
// 解码
blockMode.CryptBlocks(origin, cryted)
// pkcs7 去码
origin = PKCS7UnPadding(origin)
return string(origin)
}
// PKCS7 补码
func PKCS7Padding(cipherText []byte, blockSize int) []byte {
padding := blockSize - len(cipherText)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(cipherText, padText...)
}
// PKCS7 去码
func PKCS7UnPadding(originBytes []byte) []byte {
length := len(originBytes)
unpadding := int(originBytes[length-1])
return originBytes[:(length - unpadding)]
}
// Base64 转码
func Base64Encode(origin []byte) string {
return base64.StdEncoding.EncodeToString(origin)
}
// Base64 解码
func Base64Decode(encode string) []byte {
decode, _ := base64.StdEncoding.DecodeString(encode)
return decode
}