在Golang中,你可以使用标准库"crypto"和"crypto/cipher"来实现数据的加密和解密。以下是一个简单的示例,展示了如何使用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 {
panic(err)
}
fmt.Printf("Encrypted data: %s\n", encryptedData)
// 解密
decryptedData, err := decrypt(encryptedData, key)
if err != nil {
panic(err)
}
fmt.Printf("Decrypted data: %s\n", 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, append(iv, 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模式。你需要将"your-secret-key-123"替换为你自己的密钥。这个密钥的长度必须是16、24或32字节,以匹配AES-128、AES-192和AES-256加密算法。
要运行此示例,请在终端中执行以下命令:
go run main.go
这将输出加密后的数据和解密后的数据。请注意,这个示例仅用于演示目的,实际应用中可能需要更多的错误处理和安全性检查。