golang aes cbc pkcs5padding

前端之家收集整理的这篇文章主要介绍了golang aes cbc pkcs5padding前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main

import (
    "crypto/cipher"
    "encoding/base64"
    "crypto/aes"
    "log"
    "bytes"
)

func main() {
    txt,err := AESBase64Encrypt("bbbbaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    if err != nil{
        log.Println(err)
        return
    }
    log.Println(txt)
    var source string
    source,err = AESBase64Decrypt(txt,"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    if err != nil{
        log.Println(err)
    }
    log.Println(source)
}

func AESBase64Encrypt(origin_data string,key string)(base64_result string,err error){
    iv := []byte{1,2,3,4,5,6,7,8,9,1,6}
    var block cipher.Block
    if block,err = aes.NewCipher([]byte(key)); err != nil{
        log.Println(err)
        return
    }
    encrypt := cipher.NewCBCEncrypter(block,iv)
    var source []byte = PKCS5Padding([]byte(origin_data),16)
    var dst []byte = make([]byte,len(source))
    encrypt.CryptBlocks(dst,source)
    base64_result = base64.RawStdEncoding.EncodeToString(dst)
    return
}

func AESBase64Decrypt(encrypt_data string,key string)(origin_data string,err = aes.NewCipher([]byte(key)); err != nil{
        log.Println(err)
        return
    }
    encrypt := cipher.NewCBCDecrypter(block,iv)

    var source [] byte
    if source,err = base64.RawStdEncoding.DecodeString(encrypt_data);err != nil{
        log.Println(err)
        return
    }
    var dst []byte = make([]byte,source)
    origin_data =  string(PKCS5Unpadding(dst))
    return
}


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)]
}
原文链接:https://www.f2er.com/go/188473.html

猜你在找的Go相关文章