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
package utils
import (
"bytes"
"crypto/cipher"
"crypto/des"
"encoding/base64"
)
//利用秘钥通过DES算法实现明文的加密
//利用秘钥通过DES算法实现密文的解密
//在加密和解密之前,首先需要补码和去码的操作
// PKCS5Padding 补码
func DESPKCS5Padding(orgData []byte, blockSize int) []byte {
//abc55555
padding := blockSize - len(orgData)%8
padtxt := bytes.Repeat([]byte{byte(padding)}, padding)
return append(orgData, padtxt...)
}
// PKCS5UnPadding 去码
func DESPKCS5UnPadding(cipherTxt []byte) []byte {
length := len(cipherTxt)
unpadding := int(cipherTxt[length-1])
return cipherTxt[:length-unpadding]
//cipherTxt[:4]
}
// DesEncrypt DES加密,加密会用到补码
func DesEncrypt(orig []byte, key []byte) []byte {
//首先检验秘钥是否合法
//DES加密算法,秘钥的长度必须为8bit block.BlockSize() = 8;
block, _ := des.NewCipher(key)
//补码
origData := DESPKCS5Padding(orig, block.BlockSize())
//设置加密方式
blockMode := cipher.NewCBCEncrypter(block, key)
//加密处理
crypted := make([]byte, len(origData)) //存放加密后的密文
blockMode.CryptBlocks(crypted, origData)
return crypted
}
// DesDecrypt DES解密,解密要用到去码
func DesDecrypt(cipherTxt []byte, key []byte) []byte {
//校验key的有效性
block, _ := des.NewCipher(key)
//设置解码方式
blockMode := cipher.NewCBCDecrypter(block, key)
//创建缓冲,存放解密后的数据
orgData := make([]byte, len(cipherTxt))
//开始解密
blockMode.CryptBlocks(orgData, cipherTxt)
//去掉编码
orgData = DESPKCS5UnPadding(orgData)
return orgData
}
// GetEncryptDes 进行des加密
func GetEncryptDes(s string) string {
return base64.StdEncoding.EncodeToString(DesEncrypt([]byte(s), []byte("dbcma123")))
// 通过base64处理秘文 打印成string
// base64.StdEncoding.EncodeToString(cipherTxt)
}
// ToDesDecrypt des对称解密
func ToDesDecrypt(cipherTxt string) string {
decodeString, err := base64.StdEncoding.DecodeString(cipherTxt)
if err != nil {
}
return string(DesDecrypt(decodeString, []byte("dbcma123")))
}