package util
import (
"bytes"
"crypto/cipher"
"crypto/des"
"encoding/base64"
)
var (
iv = []byte{1, 2, 3, 4, 5, 6, 7, 8}
key = []byte("java")
)
//DES加密
func DesEncrypt(data []byte) string {
result, _ := DesEncrypt(data, key, iv)
return base64.StdEncoding.EncodeToString(result)
}
//DES解密
func DesDecrypt(base64Str string) string {
result, err := base64.StdEncoding.DecodeString(base64Str)
if err != nil {
return ""
}
origData, err := DesDecrypt(result, key, iv)
if err != nil {
return ""
}
return string(origData)
}
func DesEncrypt(origData, key, iv []byte) ([]byte, error) {
block, err := des.NewCipher(key)
if err != nil {
return nil, err
}
origData = PKCS5Padding(origData, block.BlockSize())
blockMode := cipher.NewCBCEncrypter(block, iv)
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
func DesDecrypt(crypted, key, iv []byte) ([]byte, error) {
block, err := des.NewCipher(key)
if err != nil {
return nil, err
}
blockMode := cipher.NewCBCDecrypter(block, iv)
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = PKCS5UnPadding(origData)
return origData, nil
}
func ZeroUnPadding(origData []byte) []byte {
return bytes.TrimRightFunc(origData, func(r rune) bool {
return r == rune(0)
})
}
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 := int(origData[length-1])
return origData[:(length - unpadding)]
}
转载于:https://blog.51cto.com/zhaoshiliang/1841961