go rsa加密和解密 签名和验证

本文介绍如何在Go中使用RSA进行加密、解密、签名和验证操作。示例代码详述了关键步骤,包括如何处理RSA密钥文件,确保正确格式。参考资源:https://cloud.tencent.com/developer/section/1140761,但请注意该资源示例的不完整性。
摘要由CSDN通过智能技术生成

网上关于rsa的用法很多,尤其是 https://cloud.tencent.com/developer/section/1140761,但是上面的例子不全面

package utils

import (
	"bytes"
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/hex"
	"encoding/pem"
	"fmt"
	"os"
)

func RSAEncryptOAEP(publicKeypem, labeltext, plaintext string) (ciphertext string) {
   
	publicBlock, _ := pem.Decode([]byte(publicKeypem))
	if publicBlock == nil {
   
		panic("public key error")
	}
	pub, err := x509.ParsePKIXPublicKey(publicBlock.Bytes)
	if err != nil {
   
		panic("publicKey is not  *rsa.PublicKey")
	}
	publicKey := pub.(*rsa.PublicKey)
	rng := rand.Reader

	secretMessage := []byte(plaintext)
	label := []byte(labeltext)
	cipherbyte, err := rsa.EncryptOAEP(sha256.New(), rng, publicKey, secretMessage, label)
	if err != nil {
   
		panic(fmt.Sprintf("Error from encryption: %s\n", err))
	}

	// 由于加密是随机函数,密文将是
	// 每次都不一样。
	//fmt.Printf("Ciphertext: %x\n", cipherbyte)
	ciphertext = fmt.Sprintf("%x\n", cipherbyte)
	return
}

func RSADecryptOAEP(privateKeypem, labeltext, ciphertext string) (plaintext string) {
   
	privateBlock, _ := pem.Decode([]byte(privateKeypem))
	if privateBlock == nil {
   
		panic("private key error")
	}

	privateKey, err := x509.ParsePKCS1PrivateKey(privateBlock.Bytes)
	if err != nil {
   
		panic("privateKey is not  *rsa.PrivateKey")
	}

	/*
		prkI, err := x509.ParsePKCS8PrivateKey(privateBlock.Bytes)
		if err != nil {
			panic("privateKey is not  *rsa.PrivateKey")
		}
		privateKey := prkI.(*rsa.PrivateKey)
	*/
	rng := rand.Reader
	///
	cipherByte, _ := hex.DecodeString(ciphertext)
	label := []byte(labeltext)

	plainbyte, err := rsa.DecryptOAEP(sha256.New(), rng, privateKey, cipherByte, la
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值