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