package utils

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"fmt"
)

type RSA struct {
}

// 创建私钥
var privateKey, _ = rsa.GenerateKey(rand.Reader, 2048)

// 私钥解密

func (r *RSA) Encryption(password string) string {

	encrypted, _ := base64.StdEncoding.DecodeString(password)

	decryptedText, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, encrypted)
	if err != nil {
		fmt.Println("Failed to decrypt data:", err)
		return ""
	}
	return string(decryptedText)
}

// 返回公钥

func (r *RSA) ReturnPublicKey() string {
	publicKey := &privateKey.PublicKey
	publicKeyDer, err := x509.MarshalPKIXPublicKey(publicKey)
	if err != nil {
		fmt.Println("Failed to convert public key to DER format:", err)
		return ""
	}
	publicKeyPem := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: publicKeyDer,
	}
	publicKeyPemBytes := pem.EncodeToMemory(publicKeyPem)
	return string(publicKeyPemBytes)
}
