service/library/mycrypto/rsaCrypto.go

100 lines
2.4 KiB
Go
Raw Normal View History

2023-12-21 22:17:40 +08:00
package mycrypto
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"service/library/configcenter"
"service/library/logger"
)
type RsaCrypto struct {
rsaPubKey *rsa.PublicKey
rsaPriKey *rsa.PrivateKey
}
func NewRsaCrypto(cryptoConfig *configcenter.CryptoConfig) (rsaCrypto *RsaCrypto, err error) {
rsaCrypto = &RsaCrypto{}
//读取私钥
if rsaCrypto.readRSAPriKey(cryptoConfig) != nil {
logger.Error("read rsa primary key failed!", err)
return
}
//读取公钥
rsaCrypto.readRSAPubKey()
return
}
2024-06-15 13:41:03 +08:00
func NewRsaCryptoFromString(rsaPrivateKeyStr string) (rsaCrypto *RsaCrypto, err error) {
rsaCrypto = &RsaCrypto{}
//读取私钥
rsaPriKey, err := readRSAPriKeyFromString(rsaPrivateKeyStr)
if err != nil {
logger.Error("read rsa primary key failed!", err)
return
}
//读取公钥
rsaPubKey := &rsaPriKey.PublicKey
rsaCrypto.rsaPriKey = rsaPriKey
rsaCrypto.rsaPubKey = rsaPubKey
return
}
2023-12-21 22:17:40 +08:00
func (rsaCrypto *RsaCrypto) Encrypt(msg []byte) (encryptedBytes []byte, err error) {
//公钥加密
encryptedBytes, err = rsa.EncryptPKCS1v15(rand.Reader, rsaCrypto.rsaPubKey, msg)
if err != nil {
logger.Error("EncryptByRSA failed!, err: %v", err)
return
}
return
}
func (rsaCrypto *RsaCrypto) Decrypt(encryptedBytes []byte) (decryptedBytes []byte, err error) {
if len(encryptedBytes) == 0 {
return
}
2023-12-21 22:17:40 +08:00
//私钥解密
decryptedBytes, err = rsa.DecryptPKCS1v15(rand.Reader, rsaCrypto.rsaPriKey, encryptedBytes)
if err != nil {
logger.Error("DecryptByRSA failed!, err: %v", err)
return
}
return
}
func (rsaCrypto *RsaCrypto) readRSAPubKey() (err error) {
//读取公钥
rsaCrypto.rsaPubKey = &rsaCrypto.rsaPriKey.PublicKey
return
}
func (rsaCrypto *RsaCrypto) readRSAPriKey(cryptoConfig *configcenter.CryptoConfig) (err error) {
//读取私钥
rsaPriKeyBytes, _ := base64.StdEncoding.DecodeString(cryptoConfig.RSAPrivateKey)
rsaCrypto.rsaPriKey, err = x509.ParsePKCS1PrivateKey(rsaPriKeyBytes)
if err != nil {
logger.Error("Decoding rsa primary key failed, check your config, please!, err: %v", err)
return
}
return
}
2024-06-15 13:41:03 +08:00
func readRSAPriKeyFromString(rsaPrivateKeyStr string) (rsaPriKey *rsa.PrivateKey, err error) {
//读取私钥
rsaPriKeyBytes, _ := base64.StdEncoding.DecodeString(rsaPrivateKeyStr)
rsaPriKey, err = x509.ParsePKCS1PrivateKey(rsaPriKeyBytes)
if err != nil {
logger.Error("Decoding rsa primary key failed, check your config, please!, err: %v", err)
return
}
return
}