package crypto

import (
	"agent/defines/derrs"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/pem"
	"os"
)

func EncryptWithPubKey(data []byte, pubKey *rsa.PublicKey) (res []byte, err error) {
	hash := sha256.New()
	return rsa.EncryptOAEP(hash, rand.Reader, pubKey, data, nil)
}

func LoadPubKey(pubKeyData []byte, pubKeyFile string) (key *rsa.PublicKey, err error) {
	if len(pubKeyData) > 0 {
		return LoadPubKeyFromBytes(pubKeyData)
	}
	if len(pubKeyFile) > 0 {
		return LoadPubKeyFromFile(pubKeyFile)
	}
	return nil, derrs.NewIncorrectParamsError("no public key data or file provided")
}

func LoadPubKeyFromBytes(keyBytes []byte) (key *rsa.PublicKey, err error) {
	if key, err = x509.ParsePKCS1PublicKey(keyBytes); err != nil {
		return nil, err
	}
	return key, nil
}

func LoadPubKeyFromFile(path string) (key *rsa.PublicKey, err error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	pem, _ := pem.Decode(data)
	if key, err = x509.ParsePKCS1PublicKey(pem.Bytes); err != nil {
		return nil, err
	}
	return key, nil
}
