在Golang中,您可以使用标准库中的crypto/cipher包来实现对称密码加密和解密。下面是一个使用PCBC(Propagating Cipher Block Chaining)模式进行加密和解密的示例:
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
func encrypt(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// 使用PCBC模式进行加密
mode := cipher.NewCBCEncrypter(block, key[:block.BlockSize()])
ciphertext := make([]byte, len(plaintext))
mode.CryptBlocks(ciphertext, plaintext)
return ciphertext, nil
}
func decrypt(ciphertext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// 使用PCBC模式进行解密
mode := cipher.NewCBCDecrypter(block, key[:block.BlockSize()])
plaintext := make([]byte, len(ciphertext))
mode.CryptBlocks(plaintext, ciphertext)
return plaintext, nil
}
func main() {
key := []byte("0123456789ABCDEF") // 16字节的AES密钥
plaintext := []byte("Hello World!")
ciphertext, err := encrypt(plaintext, key)
if err != nil {
fmt.Println("加密错误:", err)
return
}
fmt.Printf("加密后的结果: %x\n", ciphertext)
decryptedText, err := decrypt(ciphertext, key)
if err != nil {
fmt.Println("解密错误:", err)
return
}
fmt.Println("解密后的结果:", string(decryptedText))
}
请注意,上述代码中使用的是AES对称加密算法,并且假设明文和密钥长度都为16字节。您可以根据实际需求进行调整。
内容由零声教学AI助手提供,问题来源于学员提问