github.com/sereiner/library@v0.0.0-20200518095232-1fa3e640cc5f/security/des/des.ecb.go (about)

     1  package des
     2  
     3  import (
     4  	"crypto/des"
     5  	"encoding/hex"
     6  	"errors"
     7  	"fmt"
     8  	"strings"
     9  )
    10  
    11  // EncryptECB DES加密
    12  // input 要加密的字符串	skey 加密使用的秘钥[字符串长度必须是8的倍数]
    13  func EncryptECB(input string, skey string) (r string, err error) {
    14  	origData := []byte(input)
    15  	key := []byte(skey)
    16  	block, err := des.NewCipher(key)
    17  	if err != nil {
    18  		return "", fmt.Errorf("des NewCipher err:%v", err)
    19  	}
    20  	origData = PKCS5Padding(origData, block.BlockSize())
    21  	blockMode := NewECBEncrypter(block)
    22  	crypted := make([]byte, len(origData))
    23  	blockMode.CryptBlocks(crypted, origData)
    24  	r = strings.ToUpper(hex.EncodeToString(crypted))
    25  	return
    26  }
    27  
    28  // DecryptECB DES解密
    29  // input 要解密的字符串	skey 加密使用的秘钥[字符串长度必须是8的倍数]
    30  func DecryptECB(input string, skey string) (r string, err error) {
    31  	/*add by champly 2016年11月16日17:35:03*/
    32  	if len(input) < 1 {
    33  		return "", errors.New("解密的对象长度必须大于0")
    34  	}
    35  	/*end*/
    36  
    37  	crypted, err := hex.DecodeString(input)
    38  	if err != nil {
    39  		return "", fmt.Errorf("hex DecodeString err:%v", err)
    40  	}
    41  	key := []byte(skey)
    42  	block, err := des.NewCipher(key)
    43  	if err != nil {
    44  		return "", fmt.Errorf("des NewCipher err:%v", err)
    45  	}
    46  	blockMode := NewECBDecrypter(block)
    47  	origData := make([]byte, len(crypted))
    48  	blockMode.CryptBlocks(origData, crypted)
    49  	origData = PKCS5UnPadding(origData)
    50  	r = string(origData)
    51  	return
    52  }