Go 语言中使用 AES 加密明文并编码为 base64 字符串的方法

2025-01-09 02:08:51   小编

Go语言中使用AES加密明文并编码为base64字符串的方法

在Go语言开发中,数据加密是保障信息安全的重要手段。AES(Advanced Encryption Standard)作为一种对称加密算法,被广泛应用于数据加密领域。本文将介绍如何在Go语言中使用AES加密明文,并将加密结果编码为base64字符串。

我们需要导入必要的包:

package main

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

接下来,定义一个函数用于AES加密:

func AESEncrypt(key []byte, plaintext []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err!= nil {
        return nil, err
    }
    plaintext = PKCS7Padding(plaintext, block.BlockSize())
    ciphertext := make([]byte, len(plaintext))
    mode := cipher.NewCBCEncrypter(block, key[:aes.BlockSize])
    mode.CryptBlocks(ciphertext, plaintext)
    return ciphertext, nil
}

这里的PKCS7Padding函数用于对明文进行填充,使其长度满足AES加密的要求:

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

然后,我们可以编写主函数来进行加密和base64编码:

func main() {
    key := []byte("1234567890123456")
    plaintext := []byte("Hello, World!")
    ciphertext, err := AESEncrypt(key, plaintext)
    if err!= nil {
        panic(err)
    }
    encoded := base64.StdEncoding.EncodeToString(ciphertext)
    println(encoded)
}

在上述代码中,我们首先定义了加密密钥和明文,然后调用AESEncrypt函数进行加密,最后使用base64.StdEncoding.EncodeToString将加密结果编码为base64字符串。

通过以上步骤,我们就实现了在Go语言中使用AES加密明文并编码为base64字符串的功能。在实际应用中,可以根据需求调整密钥和明文内容,以满足不同的加密需求。也要注意密钥的安全性和保密性,避免密钥泄露导致数据安全问题。

TAGS: GO语言 AES加密 Base64编码 明文加密

欢迎使用万千站长工具!

Welcome to www.zzTool.com