golang中rsa加密怎么实现

   2025-02-07 9220
核心提示:在Golang中,可以使用crypto/rsa包来实现RSA加密。下面是一个简单的示例代码:package mainimport (crypto/randcrypto/rsacrypto

在Golang中,可以使用crypto/rsa包来实现RSA加密。下面是一个简单的示例代码:

package mainimport ("crypto/rand""crypto/rsa""crypto/x509""encoding/pem""fmt")func main() {// 生成RSA密钥对privateKey, err := rsa.GenerateKey(rand.Reader, 2048)if err != nil {fmt.Println("Failed to generate RSA key pair:", err)return}// 将私钥保存为PEM格式privateKeyPem := &pem.Block{Type:  "RSA PRIVATE KEY",Bytes: x509.MarshalPKCS1PrivateKey(privateKey),}privateKeyPemBytes := pem.EncodeToMemory(privateKeyPem)fmt.Println("Private key (PEM format):")fmt.Println(string(privateKeyPemBytes))// 将公钥保存为PEM格式publicKey := &privateKey.PublicKeypublicKeyDer, err := x509.MarshalPKIXPublicKey(publicKey)if err != nil {fmt.Println("Failed to convert public key to DER format:", err)return}publicKeyPem := &pem.Block{Type:  "PUBLIC KEY",Bytes: publicKeyDer,}publicKeyPemBytes := pem.EncodeToMemory(publicKeyPem)fmt.Println("Public key (PEM format):")fmt.Println(string(publicKeyPemBytes))// 加密数据plainText := []byte("Hello, RSA encryption!")cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)if err != nil {fmt.Println("Failed to encrypt data:", err)return}fmt.Println("Cipher text:")fmt.Println(cipherText)// 解密数据decryptedText, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, cipherText)if err != nil {fmt.Println("Failed to decrypt data:", err)return}fmt.Println("Decrypted text:")fmt.Println(string(decryptedText))}

在上面的示例代码中,首先生成了一个2048位的RSA密钥对。然后,将私钥保存为PEM格式,并打印出来。接着,将公钥保存为PEM格式,并打印出来。

然后,使用公钥对数据进行加密,输出加密后的密文。最后,使用私钥对密文进行解密,输出解密后的明文。

注意:在实际应用中,需要妥善保管私钥,避免私钥泄露。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言