go语言, 初识RSA加密
go语言, 初识RSA加密
漂泊的树叶 发表于5个月前
go语言, 初识RSA加密
  • 发表于 5个月前
  • 阅读 57
  • 收藏 1
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

简介:

    作为一名初学者,简单阅读了的RSA的加密原理,和几篇关于go语言rsa加密的博客,

写了一个很简陋的demo. 记录下来,以免忘记 

1.包含方法

    (1)公钥加密

    (2)私钥解密

    (3)私钥签名

    (4)公钥验签

    直接看代码

2.代码

2.1 加密代码

package util

import (
	"encoding/pem"
	"errors"
	"crypto/x509"
	"crypto/rsa"
	"crypto/rand"
	"crypto"
)

/**
   @param sourceBytes 原文
   @param publicKey  公钥字符串
   公钥加密
 */
func EncipherRsa(sourceBytes []byte, publicKey string) ([]byte, error)  {
	//获取公钥
	block, _ := pem.Decode([]byte(publicKey))
	if block == nil {
		return nil, errors.New("获取公钥失败")
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	pub := pubInterface.(*rsa.PublicKey)
	//声明密文,动态数组
	var cipherByte []byte
	//分段加密
	for i := 0; i < len(sourceBytes); i += 245{
		var slice []byte
		if(i + 245) < len(sourceBytes){
			slice = sourceBytes[i : i + 245]
		}else {
			slice = sourceBytes[i : len(sourceBytes)]
		}
		//Rsa加密,encryptBytes:分段密文
		encryptBytes, err := rsa.EncryptPKCS1v15(rand.Reader, pub, slice)
		if err != nil {
			return nil, err
		}
		//追加分段密文encryptBytes=>cipherByte
		cipherByte = append(cipherByte, encryptBytes...)
	}
	return cipherByte,nil
}

/**
	@param cipherByte 密文
	@param privateKey 私钥字符串
  	私钥解密,返回原文
 */
func DecipherRsa(cipherByte []byte, privateKey string) ([]byte, error) {
	//获取私钥
	block, _ := pem.Decode([]byte(privateKey))
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	//声明一个动态数组,用来存放解密之后的数据
	var source []byte
	//分段解密
	for i :=0; i < len(cipherByte); i += 256{
		var slice []byte
		if(i + 256) < len(cipherByte){
			slice = cipherByte[i : i + 256]
		}else {
			slice = cipherByte[i : len(cipherByte)]
		}
		//rsa解密
		decrypt, err := rsa.DecryptPKCS1v15(rand.Reader, priv, slice)
		if err != nil{
			return nil, err
		}
		//追加解密数据decrypt=>source
		source = append(source, decrypt...)
	}
	return source, nil
}

/**
	@param cipherText  待签名字段
	RSA私钥签名sha1
 */
func RsaSign(cipherText []byte, privateKey string) ([]byte, error) {
	//获取私钥
	block, _ := pem.Decode([]byte(privateKey))
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	//指定HASH类型  SHA1
	h := crypto.Hash.New(crypto.SHA1)
	h.Write(cipherText)
	hashed := h.Sum(nil)
	//返回签名结果
	return rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA1, hashed)
}

/**
	@param origData 待签名字段
	@param sign     签名
	公钥验签
 */
func VerifySign(origData []byte, sign []byte, publicKey string) error {
	//获取公钥
	block, _ := pem.Decode([]byte(publicKey))
	if block == nil {
		return errors.New("public key error")
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return  err
	}
	pub := pubInterface.(*rsa.PublicKey)
	//指定HASH类型  SHA1
	h := crypto.Hash.New(crypto.SHA1)
	h.Write(origData)
	hashed := h.Sum(nil)
	//返回验签结果
	err = rsa.VerifyPKCS1v15(pub, crypto.SHA1, hashed, sign)
	return err
}

2.2测试代码

package main

import (
	"util"
	"log"
	"fmt"
)

var public_key = `
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs2fv0rclnSLCCoG+tUV
IbphXbpXBeugeLTRkYE2WSSfdk5m0oyPmg15fnaoj/yhEy9vmAVGrqA4ROa3Q5V
C6vWZZXGbsiUzyloHZ63IGylRdsfX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6gqF0TK0kg53q7pA8ziE3s+IgHaNWra+wMRB5L38uRt1BEku
aU7e4MvLuXHSNsQkpajrTJ3wxttPPCMoNFniGWDdIHTvso/NbnuH46sYFWGfcrB
Kg5JsCgYEAx5DSuIQGisUiQeNDpRM9fVj9nT4Cxp7rFvKzr3gLQ5zqmmyczfAXl
G1n60C1jlxnbRbb+7ruiuWxIl4HJL0+qvziPwC+uI2NP53mTIHLojQT51hZnPP/
6i5R6IUsfIyHu7Mka2H1VqEcaDDXqXitGUc9rw7qxKA5jsb+kpf2oEkCgYEA40x
ssvZcsEE+WAmIrwsAQrqItXl6acBbhvTPNqh10mv0M3tEwjoUtZ7JkyuTigeYAM
Z/uo+K/qugMHIt9hfVDEZxZoQ2rMqYEjWEh2VUT0stCmUVNwuGxkueM+VVl7H6B
/C6kpu8wWzYg1hWSUleN6+r1gipqHdb4Cz0rp7XefECgYAvIPdyldNJsFZvwvD1
qf6KfJqgKMXVDDCuobBnjuzyEbuhrma1h6654cB54TU/InlWXOCkqTeuW6IiYJx
FQ9/p14DCqjVgNiWWUX7SsJBbhPryVn4LP+A++KNlSxX/b9yaKis+pMqgo7mmrW
ow3ovafWWG0voEZ2ZQXpQ+IF8g6QKBgEVtcFiUdTz9jN6tbAQ7s9utvS3VBtQNO
doWVURLa0moLbgTgQlz2f5lsRkNiOulCYcPTfv1P9GsWhtrd9q1KNjUN87xR9vl
z25qLHCla5XzpgfsYIbnsq1Eew2ulzoDMrAxeiTEmLMxH5L+CojGDAoSKFgkfQE
3NKhDdtJCtqtg
-----END RSA PRIVATE KEY-----
`

func main()  {

	var str = "testrsa123"

	//公钥加密
	encryptBytes, err := util.EncipherRsa([]byte(str), public_key)
	if err != nil{
		log.Fatal(err)
	}

	//私钥解密
	decryptBytes, err := util.DecipherRsa(encryptBytes, privateKey)
	if err != nil{
		log.Fatal(err)
	}
	fmt.Println("解密结果=" + string(decryptBytes))

	//私钥签名
	signBytes, err := util.RsaSign([]byte(str), privateKey)
	if err!= nil{
		log.Fatal(err)
	}

	//公钥验签
	err = util.VerifySign([]byte(str), signBytes, public_key)
	if err == nil{
		fmt.Println("签名校验成功")
	}
}

 

共有 人打赏支持
粉丝 0
博文 1
码字总数 733
×
漂泊的树叶
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: