-
Notifications
You must be signed in to change notification settings - Fork 0
/
encrypt.go
69 lines (61 loc) · 1.69 KB
/
encrypt.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
package yunzhanghu
import (
"bytes"
"crypto/cipher"
"crypto/des"
"encoding/base64"
"encoding/json"
)
// 3DES加密
func TripleDesEncrypt(origData, des3key []byte) ([]byte, error) {
block, err := des.NewTripleDESCipher(des3key)
if err != nil {
return nil, err
}
origData = PKCS5Padding(origData, block.BlockSize())
// origData = ZeroPadding(origData, block.BlockSize())
blockMode := cipher.NewCBCEncrypter(block, des3key[:8])
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
// 3DES解密
func TripleDesDecrypt(crypted, des3key []byte) ([]byte, error) {
block, err := des.NewTripleDESCipher(des3key)
if err != nil {
return nil, err
}
blockMode := cipher.NewCBCDecrypter(block, des3key[:8])
origData := make([]byte, len(crypted))
// origData := crypted
blockMode.CryptBlocks(origData, crypted)
origData = PKCS5UnPadding(origData)
// origData = ZeroUnPadding(origData)
return origData, nil
}
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)]
}
func DecryptB64TriDesTo(crypted string, des3key []byte, result interface{}) error {
desData, err := base64.StdEncoding.DecodeString(crypted)
if err != nil {
return err
}
rawData, err := TripleDesDecrypt(desData, des3key)
if err != nil {
return err
}
err = json.Unmarshal(rawData, result)
if err != nil {
return err
}
return nil
}