教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 golang实现 aes加解密,对称加密

golang实现 aes加解密,对称加密

发布时间:2023-03-13   编辑:jiaochengji.com
教程集为您提供golang实现 aes加解密,对称加密等资源,欢迎您收藏本站,我们将为您提供最新的golang实现 aes加解密,对称加密资源

直接上代码

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
}

调用

func main() {
    text := "123" // 你要加密的数据
    AesKey := []byte("#HvL%$o0oNNoOZnk#o2qbqCeQB1iXeIR") // 对称秘钥长度必须是16的倍数

    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("j4H4Tv5VcXv0oNLwB/fr g==")
    origin, err := AesDecrypt(encrypted, AesKey)
    if err != nil {
        panic(err)
    }
    fmt.Printf("解密后明文: %s\n", string(origin))
}

返回数据:

明文: 123
秘钥: #HvL%$o0oNNoOZnk#o2qbqCeQB1iXeIR
加密后: xvhqp8bT0mkEcAsNK L4fw==
解密后明文: 123
到此这篇关于“golang实现 aes加解密,对称加密”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
golang基础学习-AES加密
密码学之对称加密
PHP 数据加密的方法
C# 256 位 AES 加密与解密文件的实现代码
Python:常见的加密方式
Golang AES加密算法ECB加密模式实现
Javascript 到 PHP 加密通讯的简单实现
php aes加密类代码分享
PHP如何使用AES加密和解密
Go语言实现AES加密算法(CBC模式)

[关闭]
~ ~