-
Notifications
You must be signed in to change notification settings - Fork 1
/
crypt.go
54 lines (47 loc) · 1.29 KB
/
crypt.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
package iso8583SDK
import (
"bytes"
"crypto/cipher"
"crypto/des"
"fmt"
)
func encrypt(msg, key []byte) []byte {
var tripleDESKey []byte
tripleDESKey = append(tripleDESKey, key[:16]...)
tripleDESKey = append(tripleDESKey, key[:8]...)
encryptedMsg, err := TripleDesEncrypt(msg, tripleDESKey)
if err != nil {
fmt.Println("TripleEcbDesEncrypt error :", err.Error())
}
return encryptedMsg
}
// 3DES加密
func TripleDesEncrypt(origData, key []byte) ([]byte, error) {
block, err := des.NewTripleDESCipher(key)
if err != nil {
return nil, err
}
// origData = PKCS5Padding(origData, block.BlockSize())
origData = ZeroPadding(origData, block.BlockSize())
IV := make([]byte, 8)
blockMode := cipher.NewCBCEncrypter(block, IV)
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
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 {
return bytes.TrimFunc(origData,
func(r rune) bool {
return r == rune(0)
})
}