Go语言crypto包支持AES和RSA加密。首先介绍AES-GCM模式加解密,使用16字节密钥对数据进行加密并Base64编码;接着演示RSA非对称加密,生成2048位密钥对,公钥加密、私钥解密,并支持PEM格式保存与加载密钥,确保实际应用中的密钥管理安全。

Go语言的crypto包提供了多种加密和解密功能,常用于数据安全传输和存储。下面介绍几种常见的加密方式:AES对称加密和RSA非对称加密,并给出可运行的示例代码。
AES对称加密(CBC模式)
AES是一种对称加密算法,加密和解密使用相同的密钥。以下是使用AES-CBC模式进行加密和解密的示例:
说明: 需要密钥长度为16、24或32字节(对应AES-128、AES-192、AES-256),并使用PKCS7填充。
示例代码:
立即学习“go语言免费学习笔记(深入)”;
package mainimport ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" "io")func aesEncrypt(plaintext []byte, key []byte) (string, error) { block, err := aes.NewCipher(key) if err != nil { return "", err } gcm, err := cipher.NewGCM(block) if err != nil { return "", err } nonce := make([]byte, gcm.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { return "", err } ciphertext := gcm.Seal(nonce, nonce, plaintext, nil) return base64.StdEncoding.EncodeToString(ciphertext), nil}func aesDecrypt(ciphertext string, key []byte) ([]byte, error) { data, err := base64.StdEncoding.DecodeString(ciphertext) if err != nil { return nil, err } block, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } nonceSize := gcm.NonceSize() if len(data) < nonceSize { return nil, fmt.Errorf("ciphertext too short") } nonce, ciphertext := data[:nonceSize], data[nonceSize:] return gcm.Open(nil, nonce, ciphertext, nil)}func main() { key := []byte("example key 1234") // 16字节密钥 message := []byte("Hello, this is a secret message!") encrypted, err := aesEncrypt(message, key) if err != nil { panic(err) } fmt.Println("Encrypted:", encrypted) decrypted, err := aesDecrypt(encrypted, key) if err != nil { panic(err) } fmt.Println("Decrypted:", string(decrypted))}
RSA非对称加密
RSA是一种非对称加密算法,使用公钥加密,私钥解密。适合小数据加密或密钥交换。
说明: Go中可通过crypto/rsa和crypto/rand生成密钥对,使用公钥加密,私钥解密。
示例代码:
立即学习“go语言免费学习笔记(深入)”;
package mainimport ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "fmt" "log")func generateRSAKeys() (*rsa.PrivateKey, *rsa.PublicKey, error) { privatekey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return nil, nil, err } publickey := &privatekey.PublicKey return privatekey, publickey, nil}func rsaEncrypt(plaintext []byte, pub *rsa.PublicKey) ([]byte, error) { ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, pub, plaintext) return ciphertext, err}func rsaDecrypt(ciphertext []byte, priv *rsa.PrivateKey) ([]byte, error) { plaintext, err := rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext) return plaintext, err}func main() { // 生成密钥对 privKey, pubKey, err := generateRSAKeys() if err != nil { log.Fatal(err) } message := []byte("Secret message for RSA encryption") // 加密 encrypted, err := rsaEncrypt(message, pubKey) if err != nil { log.Fatal(err) } fmt.Println("Encrypted (base64):", base64.StdEncoding.EncodeToString(encrypted)) // 解密 decrypted, err := rsaDecrypt(encrypted, privKey) if err != nil { log.Fatal(err) } fmt.Println("Decrypted:", string(decrypted))}
保存和加载PEM格式密钥
在实际应用中,通常需要将RSA密钥保存到文件或从文件读取。PEM是常用格式。
保存私钥和公钥到PEM:
// 保存私钥func savePrivateKey(priv *rsa.PrivateKey) []byte { privBytes := x509.MarshalPKCS1PrivateKey(priv) privPem := pem.EncodeToMemory(&pem.Block{ Type: "RSA PRIVATE KEY", Bytes: privBytes, }) return privPem}// 保存公钥func savePublicKey(pub *rsa.PublicKey) []byte { pubBytes, _ := x509.MarshalPKIXPublicKey(pub) pubPem := pem.EncodeToMemory(&pem.Block{ Type: "PUBLIC KEY", Bytes: pubBytes, }) return pubPem}
从PEM加载密钥:
func loadPrivateKey(pemData []byte) (*rsa.PrivateKey, error) { block, _ := pem.Decode(pemData) return x509.ParsePKCS1PrivateKey(block.Bytes)}func loadPublicKey(pemData []byte) (*rsa.PublicKey, error) { block, _ := pem.Decode(pemData) pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return nil, err } return pubInterface.(*rsa.PublicKey), nil}
基本上就这些。通过crypto包可以实现常见加密需求,注意密钥安全管理和填充模式选择。实际项目中建议结合TLS或成熟加密库使用。
以上就是Golang crypto加密解密操作示例的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1409112.html
微信扫一扫
支付宝扫一扫