package utils

import (
    "bytes"
    "crypto/cipher"
    "crypto/des"
)

//CBC加密
func EncryptDES_CBC(data []byte, key []byte,iv []byte) ([]byte,error) {
    block, err := des.NewCipher(key)
    if err != nil {
        return nil,err
    }
    data = PKCS5Padding(data , block.BlockSize())
    //获取CBC加密模式
    mode := cipher.NewCBCEncrypter(block, iv)
    out := make([]byte, len(data))
    mode .CryptBlocks(out, data)
    return out,nil
}

//CBC解密
func DecryptDES_CBC(data []byte, key []byte,iv []byte) ([]byte,error) {
    block, err := des.NewCipher(key)
    if err != nil {
        return nil,err
    }
    mode := cipher.NewCBCDecrypter(block, iv)
    plaintext := make([]byte, len(data))
    mode.CryptBlocks(plaintext, data)
    plaintext = PKCS5UnPadding(plaintext)
    return plaintext,nil
}


//明文补码算法
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
    padding := blockSize - len(ciphertext)%blockSize
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}
//明文减码算法
func PKCS5UnPadding(origData []byte) []byte {
    length := len(origData)
    unpadding := int(origData[length-1])
    return origData[:(length - unpadding)]
}