package utils

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/pem"
	"errors"
	"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, encrypted []byte) ([]byte, error) {
	hash, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privateKey, encrypted, nil)
	if err != nil {
		return nil, err
	}
	return hash, nil
}

// 解析RSA公钥
func ParsePublicKeyFromPEM() (publicKey *rsa.PublicKey, err error) {
	pemBlock, err := os.ReadFile("./conf/rsa_public_key.pem")
	block, _ := pem.Decode(pemBlock)
	if block == nil {
		FileLog.Error("公钥解析失败")
		return nil, errors.New("公钥解析失败")
	}
	key, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	publicKey = key.(*rsa.PublicKey)
	return
}
