Golang 实现 AES 加解密的代码示例

2024-12-28 22:32:08   小编

Golang 实现 AES 加解密的代码示例

在现代的信息安全领域,加密技术起着至关重要的作用。AES(Advanced Encryption Standard)是一种广泛使用的对称加密算法,具有高效、安全的特点。在 Go 语言中,我们可以轻松地实现 AES 加解密。

我们需要导入必要的包:

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

接下来,定义密钥和明文:

key := []byte("ThisIsASecretKey")
plaintext := []byte("Hello, AES Encryption!")

加密函数如下:

func encrypt(plaintext []byte, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err!= nil {
        return nil, err
    }

    ciphertext := make([]byte, aes.BlockSize + len(plaintext))
    iv := ciphertext[:aes.BlockSize]

    stream := cipher.NewCTR(block, iv)
    stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

    return ciphertext, nil
}

解密函数与加密函数类似:

func decrypt(ciphertext []byte, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err!= nil {
        return nil, err
    }

    plaintext := make([]byte, len(ciphertext) - aes.BlockSize)
    iv := ciphertext[:aes.BlockSize]

    stream := cipher.NewCTR(block, iv)
    stream.XORKeyStream(plaintext, ciphertext[aes.BlockSize:])

    return plaintext, nil
}

在主函数中,我们调用加密和解密函数:

func main() {
    ciphertext, err := encrypt(plaintext, key)
    if err!= nil {
        panic(err)
    }

    plaintextDecrypted, err := decrypt(ciphertext, key)
    if err!= nil {
        panic(err)
    }

    // 输出加密后的十六进制字符串
    fmt.Println("Encrypted: ", hex.EncodeToString(ciphertext))
    // 输出解密后的明文
    fmt.Println("Decrypted: ", string(plaintextDecrypted))
}

通过以上代码示例,我们成功地在 Go 语言中实现了 AES 加解密的功能。在实际应用中,确保妥善保管密钥,并根据具体需求进行适当的错误处理和优化。

AES 加密算法为我们的数据安全提供了有力的保障,通过 Go 语言简洁高效的特性,能够方便地将其应用到各种需要加密的场景中。

TAGS: Golang_AES 加密 Golang_AES 解密 AES 加密_Golang AES 解密_Golang

欢迎使用万千站长工具!

Welcome to www.zzTool.com