package com.easyproject.common.utils.sign;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import lombok.extern.slf4j.Slf4j;

/**
 * 方法说明: 非对称加密 RSA
 *
 * @param
 * @author java-101
 * @return
 * @date 2024-07-03 10:40:20
 */
@Slf4j
public class AsymmetricCryptoUtils {

    private static String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANDOAJeAcYkH37TzsF7862qHvRSEIdfPxinXe7MABpPTf07fizvqESBqEFoq+GIJEAx9S5OeWXiaxFdGnKiPWgX1PPlMqXecuO+ayAPc3I0lUXKWkNMRihql0B/d58+HmG9ugps0Kgk1bkH1R48kbBnuG+is5iqqu+3UZ+meoT5pAgMBAAECgYABzUexujNHBP+GdeFKzic9UsE/aDnligUfAjb7gk+ZBROqa23t0EhVDaB1/4k7FiWidSgkWwYd7xH5YdV2WlEi/rvqFTES4/HnK5pCHptWR2yDquPcouweSpA2B/eMa62vc1a1LiuP5QS4H7U6IrJGw5YhD27SHkKhCtquEC4agQJBAOy7/x+rVaQBibmg2iqh26/WIcy6xZGSVX/nZGZJoIatxbZqdorqXuEzXSG6bV7vAmjFy22VAe7WnnNp3gqEYsECQQDhzCIetVqFxGeqO5cegHQ7bnbJdfEUhxM3j8mrAO+v9M/eACTOkttiGQQXuJE6PvuQP55ihQh31wzYjTCliE2pAkEAmzpmfoCdRk5P3a1QgNXjNHhHb3QkqmB2ucijd8LdhJIba5KBqnMlxaslbUFOCArW3Jad3nvvaYnHGkyX8PN/wQJBANfMjBODSeespVLaLvzU0cF3OooicW0oB2LDxn7rnygwtnW693KCgq+HrxSorgvX4/+h/dK0yDoYysswbXzW/zkCQD7RGNmyXnmIfkvBjl/4uqLX6zSKztcn9WzM120wz1hjRZh5YrzN8WyixoLfkbJLINJQDnif0dnEFOuz6CZklzU=";
    private static String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQzgCXgHGJB9+087Be/Otqh70UhCHXz8Yp13uzAAaT039O34s76hEgahBaKvhiCRAMfUuTnll4msRXRpyoj1oF9Tz5TKl3nLjvmsgD3NyNJVFylpDTEYoapdAf3efPh5hvboKbNCoJNW5B9UePJGwZ7hvorOYqqrvt1GfpnqE+aQIDAQAB";

    /**
     * 方法说明: 加密 - 私钥加密
     *
     * @param
     * @return
     * @author java-101
     * @date 2024-07-03 11:01:09
     */
    public static String encryptRSA(String content) {
        String str = null;
        if (StrUtil.isEmpty(content)) {
            return null;
        }
        try {
            RSA rsa = new RSA(PRIVATE_KEY, null);
            str = rsa.encryptBase64(content, KeyType.PrivateKey);
        } catch (Exception e) {
            log.error("在进行RSA加密时，出现异常：{}", e.getMessage());
        }
        return str;
    }

    /**
     * 方法说明: 加密 - 公钥解密
     *
     * @param
     * @return
     * @author java-101
     * @date 2024-07-03 11:03:31
     */
    public static String decryptRSA(String encrypt) {
        String str = null;
        if (StrUtil.isEmpty(encrypt)) {
            return null;
        }
        try {
            RSA rsa = new RSA(null, PUBLIC_KEY);
            str = rsa.decryptStr(encrypt, KeyType.PublicKey);
        } catch (Exception e) {
            log.error("在进行RSA解密时，出现异常：{}", e.getMessage());
        }
        return str;
    }

    public static void main(String[] args) {
        String content = "0xafB366C1ca4bcEFf911c3727A26aC196b36f4865";
        String str = encryptRSA(content);
        Console.log("加密后 ===>> {}，长度：{}",str,str.length());
        String str2 = decryptRSA(str);
        Console.log("解密后 ===>> {}",str2);
    }
}
