123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- package auth
- import (
- "crypto/rand"
- "crypto/rsa"
- "crypto/x509"
- "encoding/base64"
- "encoding/pem"
- "errors"
- logger "eta/eta_mini_ht_api/common/component/log"
- "os"
- )
- // EncryptWithRSA 使用 RSA 公钥加密数据
- func EncryptWithRSA(publicKey *rsa.PublicKey, data []byte) ([]byte, error) {
- encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, data)
- if err != nil {
- return nil, err
- }
- return encrypted, nil
- }
- // DecryptWithRSA 使用 RSA 私钥解密数据
- func DecryptWithRSA(privateKey *rsa.PrivateKey, encryptedText string) (plaintext []byte, err error) {
- encryptBytes, _ := base64.StdEncoding.DecodeString(encryptedText)
- maxChunkSize := privateKey.Size()
- for len(encryptBytes) > 0 {
- chunkSize := maxChunkSize
- if len(encryptBytes) < chunkSize {
- chunkSize = len(encryptBytes)
- }
- encryptedChunk := encryptBytes[:chunkSize]
- encryptBytes = encryptBytes[chunkSize:]
- var decryptedChunk []byte
- decryptedChunk, err = rsa.DecryptPKCS1v15(rand.Reader, privateKey, encryptedChunk)
- if err != nil {
- logger.Error("RSA解密失败", err)
- return
- }
- plaintext = append(plaintext, decryptedChunk...)
- }
- return
- }
- // ParsePrivateKeyFromPEM 解析RSA公钥
- func ParsePrivateKeyFromPEM() (privateKey *rsa.PrivateKey, err error) {
- pemBlock, err := os.ReadFile("./conf/rsa_private_key.pem")
- block, _ := pem.Decode(pemBlock)
- if block == nil {
- logger.Error("私钥解析失败")
- return nil, errors.New("私钥解析失败")
- }
- privateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
- if err != nil {
- return nil, err
- }
- return
- }
- func ParsePrivateKey(configPath string) (privateKey *rsa.PrivateKey, err error) {
- pemBlock, err := os.ReadFile(configPath)
- block, _ := pem.Decode(pemBlock)
- if block == nil {
- logger.Error("私钥解析失败")
- return nil, errors.New("私钥解析失败")
- }
- privateInfo, err := x509.ParsePKCS8PrivateKey(block.Bytes)
- if err != nil {
- return nil, err
- }
- privateKey = privateInfo.(*rsa.PrivateKey)
- return
- }
- func ParsePublicKey(configPath string) (publicKey *rsa.PublicKey, err error) {
- pemBlock, err := os.ReadFile(configPath)
- block, _ := pem.Decode(pemBlock)
- if block == nil {
- logger.Error("公钥解析失败")
- return nil, errors.New("公钥解析失败")
- }
- key, err := x509.ParsePKIXPublicKey(block.Bytes)
- if err != nil {
- return nil, err
- }
- publicKey = key.(*rsa.PublicKey)
- return
- }
- // ParsePublicKeyFromPEM 解析RSA公钥
- func ParsePublicKeyFromPEM() (publicKey *rsa.PublicKey, err error) {
- pemBlock, err := os.ReadFile("./conf/rsa_public_key.pem")
- block, _ := pem.Decode(pemBlock)
- if block == nil {
- logger.Error("公钥解析失败")
- return nil, errors.New("公钥解析失败")
- }
- key, err := x509.ParsePKIXPublicKey(block.Bytes)
- if err != nil {
- return nil, err
- }
- publicKey = key.(*rsa.PublicKey)
- return
- }
|