在Golang中,可以使用标准库"crypto"和"crypto/cipher"来实现数据的加密和解密。以下是一个使用AES-GCM模式进行加密和解密的示例:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
)
func main() {
key := []byte("your-secret-key") // 用于加密和解密的密钥,长度必须为16、24或32字节
plaintext := []byte("Hello, World!") // 需要加密的数据
// 加密
ciphertext, err := encrypt(key, plaintext)
if err != nil {
fmt.Println("Encryption error:", err)
return
}
fmt.Println("Encrypted data:", hex.EncodeToString(ciphertext))
// 解密
decrypted, err := decrypt(key, ciphertext)
if err != nil {
fmt.Println("Decryption error:", err)
return
}
fmt.Println("Decrypted data:", string(decrypted))
}
func encrypt(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, aesGCM.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
ciphertext := aesGCM.Seal(nonce, nonce, plaintext, nil)
return ciphertext, nil
}
func decrypt(key, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := aesGCM.NonceSize()
if len(ciphertext) < nonceSize {
return nil, fmt.Errorf("ciphertext too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}
在这个示例中,我们使用了AES-GCM模式进行加密和解密。首先,我们创建了一个AES密码块,然后使用GCM模式创建了一个cipher.GCM对象。接下来,我们生成了一个随机的nonce(一次性随机数),并使用它对明文进行加密。加密后的数据包括nonce和实际的密文。解密时,我们从密文中提取nonce,并使用它对密文进行解密。
注意:在实际应用中,密钥管理非常重要。请确保使用安全的方式存储和管理密钥。此外,这个示例仅用于演示目的,实际应用中可能需要更多的错误处理和安全性检查。