123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- // Copyright 2019 github.com. All rights reserved.
- // Use of this source code is governed by github.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)]
- }
|