go语言AES CBC模式加解密数据实现

   在多可文档系统中文件接口需要和其他系统实现用户统一登录,其他数据加密传输,要保障算法和数据的一致性    对系统接口使用有很大帮助。系统选择使用AES加密算法的CBC模式(128位密钥),实现各系统间加密数据的传输。多可提供各种语言的算法实现,以下是go语言的具体算法实现(其他语言参考博主相关文章):


package main

import (
    "bytes"
    "crypto/aes"
    "crypto/cipher"
    "encoding/hex"
    "fmt"
)

const ( 
    iv  = "1234567890ABCDEF" //16位
)

// PKCS5填充方式
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
    padding := blockSize - len(ciphertext)%blockSize
    //填充
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)

    return append(ciphertext, padtext...)
}

// Zero填充方式
func ZeroPadding(ciphertext []byte, blockSize int) []byte {
    padding := blockSize - len(ciphertext)%blockSize
    //填充
    padtext := bytes.Repeat([]byte{0}, padding)

    return append(ciphertext, padtext...)
}

// PKCS5 反填充
func PKCS5UnPadding(origData []byte) []byte {
    length := len(origData)
    unpadding := int(origData[length-1])
    return origData[:(length - unpadding)]
}

// Zero反填充
func ZeroUnPadding(origData []byte) []byte {
    length := len(origData)
    unpadding := int(origData[length-1])
    return origData[:(length - unpadding)]
}

// 加密
func AesEncrypt(encodeStr string, key []byte) (string, error) {
    encodeBytes := []byte(encodeStr)
    //根据key 生成密文
    block, err := aes.NewCipher(key)
    if err != nil {
        return "", err
    }

    blockSize := block.BlockSize()
    encodeBytes = ZeroPadding(encodeBytes, blockSize) //PKCS5Padding(encodeBytes, blockSize)

    blockMode := cipher.NewCBCEncrypter(block, []byte(iv))
    crypted := make([]byte, len(encodeBytes))
    blockMode.CryptBlocks(crypted, encodeBytes)

    hexstr := fmt.Sprintf("%x", crypted)
    return hexstr, nil
    //return base64.StdEncoding.EncodeToString(crypted), nil
}

// 解密
func AesDecrypt(decodeStr string, key []byte) ([]byte, error) {
    //decodeBytes, err := base64.StdEncoding.DecodeString(decodeStr)//先解密base64
    decodeBytes, err := hex.DecodeString(decodeStr)
    if err != nil {
        return nil, err
    }
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }
    blockMode := cipher.NewCBCDecrypter(block, []byte(iv))
    origData := make([]byte, len(decodeBytes))

    blockMode.CryptBlocks(origData, decodeBytes)
    origData = ZeroUnPadding(origData) // origData = PKCS5UnPadding(origData)
    return origData, nil
}

func main() {
    str := "多可文档管理系统"
    es, _ := AesEncrypt(str, []byte("2018201820182018"))  //16位key 
    fmt.Println(es) // 8lCuwh5+vZrZmU1J9c9Alw==

    ds, _ := AesDecrypt(es, []byte("2018201820182018"))
    fmt.Println(string(ds))
}