在Golang中,可以使用标准库"crypto"来实现数据的加密和解密。以下是一个使用AES加密算法的示例:
首先,确保你的系统已经安装了Go语言环境。然后,创建一个名为main.go的文件,并将以下代码粘贴到文件中:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
func main() {
key := []byte("your-secret-key-123") // 用于加密和解密的密钥,长度必须是16、24或32字节
plaintext := "Hello, World!" // 需要加密的数据
encryptedData, err := encrypt(plaintext, key)
if err != nil {
fmt.Println("加密失败:", err)
return
}
fmt.Println("加密后的数据:", encryptedData)
decryptedData, err := decrypt(encryptedData, key)
if err != nil {
fmt.Println("解密失败:", err)
return
}
fmt.Println("解密后的数据:", decryptedData)
}
func encrypt(plaintext string, key []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
plaintextBytes := []byte(plaintext)
padding := aes.BlockSize - len(plaintextBytes)%aes.BlockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
plaintextBytes = append(plaintextBytes, padText...)
ciphertext := make([]byte, len(plaintextBytes))
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext, plaintextBytes)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
func decrypt(ciphertext string, key []byte) (string, error) {
ciphertextBytes, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
if len(ciphertextBytes) < aes.BlockSize {
return "", fmt.Errorf("ciphertext too short")
}
iv := ciphertextBytes[:aes.BlockSize]
ciphertextBytes = ciphertextBytes[aes.BlockSize:]
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertextBytes, ciphertextBytes)
padding := int(ciphertextBytes[len(ciphertextBytes)-1])
ciphertextBytes = ciphertextBytes[:len(ciphertextBytes)-padding]
return string(ciphertextBytes), nil
}
在上面的代码中,我们使用了AES加密算法,并采用了CBC模式。请确保你的密钥长度是16、24或32字节。在这个示例中,我们使用了一个固定的密钥,但在实际应用中,你应该使用一个安全的密钥管理方法。
要运行此示例,请在终端中执行以下命令:
go run main.go
这将输出加密后的数据和解密后的数据。请注意,这个示例仅用于演示目的,实际应用中可能需要更多的错误处理和安全性检查。