0
点赞
收藏
分享

微信扫一扫

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

Go 语言入门很简单:AES加密和解密_十六进制

引言

Advanced Encryption Standard, AES 又名 Rijndael 是 NIST 于 2001 年创建的一种加密算法。它使用 128 位数据块进行加密,是一种对称块密码。在这篇文章中,我们将在 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)
}

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

Go 语言入门很简单:AES加密和解密_字符串_02

在 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 加密的密文。

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

Go 语言入门很简单:AES加密和解密_字符串_03

完整代码

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

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
举报

相关推荐

0 条评论