Go 语言入门很简单:AES加密和解密

3,652 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第 7 天,点击查看活动详情

引言

Advanced Encryption Standard, AES 又名 Rijndael 是 NIST 于 2001 年创建的一种加密算法。它使用 128 位数据块进行加密,是一种对称块密码。

AES 算法是一种迭代的对称密钥块密码,它支持 128、192 和 256 位的加密密钥(秘密密钥),以对 128 位的块中的数据进行加密和解密。

  • AES 优点:算法公开、计算量小、加密速度快、加密效率高。
  • AES 缺点:发送方和接收方必须商定好密钥,然后使双方都能保存好密钥,密钥管理成为双方的负担。

在这篇文章中,我们将在 Go 中使用 AES 加密和解密数据。通过使用需要 crypto/aes 包才能使其工作。

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

我们还将使用十六进制编码将数据编码为字符串。

使用 AES 加密消息

现在要使用加密,我们需要密钥是 32 位的。密钥将被发送到密码以对明文进行编码。

// cipher key
key := "thisis32bitlongpassphraseimusing"
 
// plaintext
pt := "This is a secret"
 
c := EncryptAES([]byte(key), pt)

这里的 EncryptAES 函数如下:

func EncryptAES(key []byte, plaintext string) string {
        // create cipher
    c, err := aes.NewCipher(key)
    CheckError(err)
        
        // allocate space for ciphered data
    out := make([]byte, len(plaintext))
 
        // encrypt
    c.Encrypt(out, []byte(plaintext))
        // return hex string
    return hex.EncodeToString(out)
}

打印密文时,它将产生如下输出:

在 AES 中解密消息

现在,我们将解密使用 AES 算法加密的消息。这是执行此操作的代码。

func DecryptAES(key []byte, ct string) {
    ciphertext, _ := hex.DecodeString(ct)
 
    c, err := aes.NewCipher(key)
    CheckError(err)
 
    pt := make([]byte, len(ciphertext))
    c.Decrypt(pt, ciphertext)
 
    s := string(pt[:])
    fmt.Println("DECRYPTED:", s)
}

此函数从十六进制字符串中解密 AES 加密的密文。

现在,当使用它时,它将产生如下输出:

完整代码

该程序的完整源代码如下:

package main
 
import (
    "crypto/aes"
    "encoding/hex"
    "fmt"
)
 
func main() {
 
    // cipher key
    key := "thisis32bitlongpassphraseimusing"
 
    // plaintext
    pt := "This is a secret"
 
    c := EncryptAES([]byte(key), pt)
 
    // plaintext
    fmt.Println(pt)
 
    // ciphertext
    fmt.Println(c)
 
    // decrypt
    DecryptAES([]byte(key), c)
}
 
func EncryptAES(key []byte, plaintext string) string {
 
    c, err := aes.NewCipher(key)
    CheckError(err)
 
    out := make([]byte, len(plaintext))
 
    c.Encrypt(out, []byte(plaintext))
 
    return hex.EncodeToString(out)
}
 
func DecryptAES(key []byte, ct string) {
    ciphertext, _ := hex.DecodeString(ct)
 
    c, err := aes.NewCipher(key)
    CheckError(err)
 
    pt := make([]byte, len(ciphertext))
    c.Decrypt(pt, ciphertext)
 
    s := string(pt[:])
    fmt.Println("DECRYPTED:", s)
}
 
func CheckError(err error) {
    if err != nil {
        panic(err)
    }
}

运行该代码,结果如下:

$ go run main.go         
This is a secret
145149d64a1a3c4025e67665001a3167
DECRYPTED: This is a secret

总结

本文通过介绍 Go 语言提供了 crypto/aes 包,利用 EncryptAES 函数对字符加密进行加密,利用 DecryptAES 函数进行解密。