golang實(shí)現(xiàn) aes加解密,對(duì)稱加密

直接上代碼

package main

import (
    "bytes"
    "crypto/aes"
    "crypto/cipher"
    "encoding/base64"
    "fmt"
    "strconv"
)

func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
    padding := blockSize - len(ciphertext)%blockSize
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}

func PKCS7UnPadding(origData []byte) []byte {
    length := len(origData)
    unpadding := int(origData[length-1])
    return origData[:(length - unpadding)]
}

//AES加密,CBC
func AesEncrypt(origData, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }
    blockSize := block.BlockSize()
    origData = PKCS7Padding(origData, blockSize)
    blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
    crypted := make([]byte, len(origData))
    blockMode.CryptBlocks(crypted, origData)
    return crypted, nil
}

//AES解密
func AesDecrypt(crypted, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }
    blockSize := block.BlockSize()
    blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
    origData := make([]byte, len(crypted))
    blockMode.CryptBlocks(origData, crypted)
    origData = PKCS7UnPadding(origData)
    return origData, nil
}

調(diào)用

func main() {
    text := "123" // 你要加密的數(shù)據(jù)
    AesKey := []byte("#HvL%$o0oNNoOZnk#o2qbqCeQB1iXeIR") // 對(duì)稱秘鑰長(zhǎng)度必須是16的倍數(shù)

    fmt.Printf("明文: %s\n秘鑰: %s\n", text, string(AesKey))
    encrypted, err := AesEncrypt([]byte(text), AesKey)
    if err != nil {
        panic(err)
    }
    fmt.Printf("加密后: %s\n", base64.StdEncoding.EncodeToString(encrypted))
    //encrypteds, _ := base64.StdEncoding.DecodeString("xvhqp8bT0mkEcAsNK+L4fw==")
    origin, err := AesDecrypt(encrypted, AesKey)
    if err != nil {
        panic(err)
    }
    fmt.Printf("解密后明文: %s\n", string(origin))
}

返回?cái)?shù)據(jù):

明文: 123
秘鑰: #HvL%$o0oNNoOZnk#o2qbqCeQB1iXeIR
加密后: xvhqp8bT0mkEcAsNK+L4fw==
解密后明文: 123
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容