在Golang中,密钥共享(Key Sharing)通常使用对称加密算法来实现。以下是一个示例代码:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func main() {
key := generateRandomKey(32) // 生成随机的32字节密钥
plainText := []byte("Hello, world!")
fmt.Println("原始文本:", string(plainText))
cipherText, err := encrypt(key, plainText)
if err != nil {
fmt.Println("加密错误:", err)
return
}
fmt.Println("加密后的文本:", cipherText)
decryptedText, err := decrypt(key, cipherText)
if err != nil {
fmt.Println("解密错误:", err)
return
}
fmt.Println("解密后的文本:", decryptedText)
}
// 生成指定长度的随机字节序列作为密钥
func generateRandomKey(length int) []byte {
key := make([]byte, length)
if _, err := rand.Read(key); err != nil {
panic(err.Error())
}
return key
}
// 使用AES算法对明文进行加密
func encrypt(key, plaintext []byte) ([]byte, error) {
blockCipher, _ := aes.NewCipher(key)
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
initializationVector := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, initializationVector); err != nil {
return nil, err
}
mode := cipher.NewCBCEncrypter(blockCipher, initializationVector)
mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
return ciphertext, nil
}
// 使用AES算法对密文进行解密
func decrypt(key, ciphertext []byte) ([]byte, error) {
blockCipher, _ := aes.NewCipher(key)
initializationVector := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
mode := cipher.NewCBCDecrypter(blockCipher, initializationVector)
decryptedText := make([]byte, len(ciphertext))
mode.CryptBlocks(decryptedText, ciphertext)
return decryptedText, nil
}
这个示例使用AES算法(具体使用的是AES-256,因为生成了一个32字节的密钥)来加密和解密数据。在实际应用中,请确保妥善管理和保护密钥,并进行适当的错误处理。
内容由零声教学AI助手提供,问题来源于学员提问




