golang 非对称加密应用

golang rsa 操作

秘钥创建管理,消息加密解密

package common

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"errors"
	"github.com/sirupsen/logrus"
)

func logger() *conf.GLogger {
	return conf.GetLogger()
}

// RSAKey rsa key
type RSAKey struct {
	publicKey  *rsa.PublicKey
	privateKey *rsa.PrivateKey
	pv         string
	pb         string
}

var prsa *RSAKey

// GetPublicKey get public key
func GetPublicKey() string {
	return prsa.pb
}

func init() {
	prsa = new(RSAKey)
	pv, pb := GenerateRsaKeyPair()
	prsa.publicKey = pb
	prsa.privateKey = pv
	pvString := ExportRsaPrivateKeyAsPemStr(pv)
	pbString, err := ExportRsaPublicKeyAsPemStr(pb)
	if err != nil {
		logger().Fatalln("create public key error")
	}
	prsa.pb = pbString
	prsa.pv = pvString
}

func GenerateRsaKeyPair() (*rsa.PrivateKey, *rsa.PublicKey) {
	privkey, _ := rsa.GenerateKey(rand.Reader, conf.RSAKEYLENGTH) //RSAKEYLENGTH = 2048
	return privkey, &privkey.PublicKey
}

func ExportRsaPrivateKeyAsPemStr(privkey *rsa.PrivateKey) string {
	privkey_bytes := x509.MarshalPKCS1PrivateKey(privkey)
	privkey_pem := pem.EncodeToMemory(
		&pem.Block{
			Type:  "RSA PRIVATE KEY",
			Bytes: privkey_bytes,
		},
	)
	return string(privkey_pem)
}

func ParseRsaPrivateKeyFromPemStr(privPEM string) (*rsa.PrivateKey, error) {
	block, _ := pem.Decode([]byte(privPEM))
	if block == nil {
		return nil, errors.New("failed to parse PEM block containing the key")
	}

	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}

	return priv, nil
}

func ExportRsaPublicKeyAsPemStr(pubkey *rsa.PublicKey) (string, error) {
	pubkey_bytes, err := x509.MarshalPKIXPublicKey(pubkey)
	if err != nil {
		return "", err
	}
	pubkey_pem := pem.EncodeToMemory(
		&pem.Block{
			Type:  "RSA PUBLIC KEY",
			Bytes: pubkey_bytes,
		},
	)

	return string(pubkey_pem), nil
}

func ParseRsaPublicKeyFromPemStr(pubPEM string) (*rsa.PublicKey, error) {
	block, _ := pem.Decode([]byte(pubPEM))
	if block == nil {
		return nil, errors.New("failed to parse PEM block containing the key")
	}

	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}

	switch pub := pub.(type) {
	case *rsa.PublicKey:
		return pub, nil
	default:
		break // fall through
	}
	return nil, errors.New("Key type is not RSA")
}

// RSAEncode encode msg with public key
func RSAEncode(msg string, key *rsa.PublicKey) []byte {
	if len(msg) == 0 {
		return []byte{}
	}
	if key == nil {
		key = prsa.publicKey
	}
	r := rand.Reader
	result, err := rsa.EncryptPKCS1v15(r, key, []byte(msg))
	if err != nil {
		logger().WithFields(logrus.Fields{"msg": msg, "error": err.Error()}).Errorln("encode msg error")
		return nil
	}
	return result
}

// RSADecode decode msg with private key
func RSADecode(msg string, key *rsa.PrivateKey) []byte {
	if len(msg) == 0 {
		return []byte{}
	}
	if key == nil {
		key = prsa.privateKey
	}
	r := rand.Reader
	result, err := rsa.DecryptPKCS1v15(r, key, []byte(msg))
	if err != nil {
		logger().WithFields(logrus.Fields{"msg": msg, "error": err.Error()}).Errorln("decode msg error")
		return nil
	}
	return result
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值