// Copyright 2019 getensh.com. All rights reserved. // Use of this source code is governed by getensh.com. package util import ( "bytes" "crypto/cipher" "crypto/des" ) // CBCDesEncrypt des加密, mode: cbc func CBCDesEncrypt(key, iv, plainText []byte) ([]byte, error) { block, err := des.NewCipher(key) if err != nil { return nil, err } blockSize := block.BlockSize() origData := pkcs5Padding(plainText, blockSize) blockMode := cipher.NewCBCEncrypter(block, iv) cryted := make([]byte, len(origData)) blockMode.CryptBlocks(cryted, origData) return cryted, nil } // CBCDesDecrypt des解密, mode: cbc func CBCDesDecrypt(key, iv, cipherText []byte) ([]byte, error) { block, err := des.NewCipher(key) if err != nil { return nil, err } blockMode := cipher.NewCBCDecrypter(block, iv) origData := make([]byte, len(cipherText)) blockMode.CryptBlocks(origData, cipherText) origData = pkcs5UnPadding(origData) return origData, nil } func pkcs5Padding(src []byte, blockSize int) []byte { padding := blockSize - len(src)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(src, padtext...) } func pkcs5UnPadding(src []byte) []byte { length := len(src) unpadding := int(src[length-1]) return src[:(length - unpadding)] }