package rsa

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) Decrypt(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)
}

func parsePublicKey(pemData string) *rsa.PublicKey {
	// 将字符串转换为字节切片
	block, _ := pem.Decode([]byte(pemData))
	if block == nil || block.Type != "PUBLIC KEY" {
		return nil
	}

	// 解析DER编码的公钥
	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil
	}

	// 类型断言为*rsa.PublicKey
	rsaPub, ok := pub.(*rsa.PublicKey)
	if !ok {
		return nil
	}

	return rsaPub
}

func (r *RSA) Encryption(data []byte) []byte {
	key := parsePublicKey(r.ReturnPublicKey())

	encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, key, data)
	if err != nil {
		panic(err)
	}
	return encryptedData
}
