package utils import ( "bytes" "crypto/des" "encoding/hex" "errors" "fmt" ) const ( DES_CRYPT_KEY = "w$D5%8x@" ) func DesEcbDecrypt(src string, key ...string) (result string, err error) { if len(key) == 0 { return DES_ECB{}.DecryptDES_ECB(src, DES_CRYPT_KEY) } else { return DES_ECB{}.DecryptDES_ECB(src, key[0]) } } type DES_ECB struct { } //DecryptDES_ECB ECB解密 func (d DES_ECB) DecryptDES_ECB(src, key string) (result string, err error) { defer func() { if defErr := recover(); defErr != nil { fmt.Printf("DecryptDES_ECB_V2 panic info:%v\n", defErr) result = "" err = errors.New("DecryptDES_ECB_V2 err") } }() data, err := hex.DecodeString(src) if err != nil { return "", err } keyByte := []byte(key) block, err := des.NewCipher(keyByte) if err != nil { return "", err } bs := block.BlockSize() if len(data)%bs != 0 { return "", errors.New("crypto/cipher: input not full blocks") } out := make([]byte, len(data)) dst := out for len(data) > 0 { block.Decrypt(dst, data[:bs]) data = data[bs:] dst = dst[bs:] } out = d.PKCS5UnPadding(out) return string(out), nil } //明文补码算法 func (d DES_ECB) PKCS5Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } //明文减码算法 func (d DES_ECB) PKCS5UnPadding(origData []byte) []byte { length := len(origData) unpadding := int(origData[length-1]) return origData[:(length - unpadding)] }