在Golang中,可以使用标准库"crypto"来实现数据的加密和解密。以下是一个使用AES加密算法的示例:
首先,确保已经安装了Golang。然后,创建一个名为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("Error encrypting data:", err)
return
}
fmt.Println("Encrypted data:", encryptedData)
decryptedData, err := decrypt(encryptedData, key)
if err != nil {
fmt.Println("Error decrypting data:", err)
return
}
fmt.Println("Decrypted data:", 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)
ciphertext := make([]byte, len(plaintextBytes)+padding)
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[padding:], append(plaintextBytes, padtext...))
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
}
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
这将输出加密后的数据和解密后的数据。请注意,这个示例仅用于演示目的,实际应用中可能需要更多的错误处理和安全性检查。