package com.ruoyi.web.controller.tool;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import java.nio.charset.StandardCharsets;

public class RSAUtils {

    private static final String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIBn5u155EG3BpLJ56jL6qXS8yOpAwrVCm3JxfbxlvYhB5X6CCAfIWm4qb4+xenurfi6inRY9oohdTekN/RZTLqFqWuCywVggWXoHDrIuF+J/lBy8ZzrTiyIQWk4ZvFYZSFW88v8dTq6Nxi1mmIP0cvRBV1tZbO2+TnM9iNAjb93AgMBAAECgYA3dSierkNwQm07XqqIE7I/dlF+uFNRDVwYuMmgcw1BNljBZKC3xto2gAQH37K461YGFAMSZw3r8LFgm7Ny/FKPq5RR/lL0mJxlMiMTif7qHKpbgiYJJcdyRTFpndrSM66ksmhd+C/xdil6RfKs9zekv7+/s22TPLZHXvNmVhLcKQJBAMFpnKRF2fwzYhxdJcU2rQ+VChat7zcnlpjzy7P7fQrdULdVIC4Zq3dMmW2ntqMnS7Rp6x8XjhBiNfznr8g2k8UCQQCp9RsP24aLaZxgy243pKS+XbuSCX5eCMHLRf4eD54Z6neXMJ2/BO1UomjtuypRSIX+/dX2vpkuNtGNHxJriC4LAkB1qgiPr6cj1Sa01r4psk+qkSMoFPzY8w6dUoP0pOS3fVijj/gZ06gK1eDpYwSrUTavNVjC+5ODyBvMFi9MgFd5AkB5bHoHHEnFtJBavzxhWKmyr/jgXxP/TrZV6g2hoHrN/SuvwrYQ0Q5WVyosHnofVHcXNHb3MDj0QYn5Duf0F3j9AkBurudGff/b2FJfiLqtraJVlALmHyL7HFQu9b52uE0SkamR887dupGSANgkOwqLbNX53h4/eI0MLzG9e5lL20Zl";
    private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCAZ+bteeRBtwaSyeeoy+ql0vMjqQMK1QptycX28Zb2IQeV+gggHyFpuKm+PsXp7q34uop0WPaKIXU3pDf0WUy6halrgssFYIFl6Bw6yLhfif5QcvGc604siEFpOGbxWGUhVvPL/HU6ujcYtZpiD9HL0QVdbWWztvk5zPYjQI2/dwIDAQAB";

    public static String encrypt(String text) {
        RSA rsa = new RSA(privateKey, publicKey);
        byte[] encrypt = rsa.encrypt(StrUtil.bytes(text, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
        return bytesToBase64(encrypt);
    }

    public static String decrypt(String encrypt) {
        RSA rsa = new RSA(privateKey, publicKey);
        byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey);
        return new String(decrypt, StandardCharsets.UTF_8);
    }

    private static String bytesToBase64(byte[] bytes) {
        byte[] encodedBytes = java.util.Base64.getEncoder().encode(bytes);
        return new String(encodedBytes, StandardCharsets.UTF_8);
    }

    private static byte[] base64ToBytes(String base64Str) {
        byte[] bytes = base64Str.getBytes(StandardCharsets.UTF_8);
        return java.util.Base64.getDecoder().decode(bytes);
    }

}
