package org.linlinjava.jz.core.util;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAUtil {

    public static void main(String[] args) throws Exception {
        String src = "data=FFkrLNn0wqwS1FSCbqnPiCsU1DsX5HjXvP333v29cMsnOFlZUJqzDStXhUXc5XQYV6nj4UCFOdanxvQDXSgtKFM/IdK/PZz5S56fflgUXVA2iDr8S+2kAXhd7/M0jDaJXqsaiExMg08uee0boAj2enKRW2Q2Kq/zeB2e+5BCc+0Xn3sGdy90GIewhyrxbD1AueFZO9cS8NnvMJAxXz5/nGXWXeVTQtwTwzolastqb0qgi59HSbcssnyv9y4Lr3a1OGy4nI+uEIaryzKCUIUUVyh36VTKcK0IZATjsdb87WwWW7GwPH4sIGKHYF8r9puABL99bslgFsO0H1fA1Sa8xCqkxbubCZRWMlfuXh7ykeRgEtHDuIwU5lUIDLreUJMEvt15FNTaa3+XnJZsykT0bi/41bT4Y+8QXOY27wn2dNzDkyfJkU4Ur/OXeAHG0dXB3gzrLqrqDUbtdEDS/DWVNdRuT2Msg5H+vg/53GNyzQj+AS6/gDRlB+1hEO8ntF+hRpuWvpdONQi3/afOrv02nhFH97Hry0Zn585M2V0a0tdeG0aQgBmehPhyzEOoT9cH2DkwDr9Px0BgJx/yKiMNiZYPYxcvU1RHEvld4KhybJk=&mess=eLs47OgXy10LPi6Unnh6Ao58&timestamp=1592444447&key=40cM782hxNpwZoYH9kqxob75gtcmTH6X";
        String sign = sign(src, getTrimKey(privateKey));
        System.out.println("密文="+sign);
        System.out.println("验签结果="+verify(src, sign, getTrimKey(publicKey)));
    }

    public static String sign(String content, String privateKeyPem) {
        try {
            byte[] encodedKey = privateKeyPem.getBytes();
            encodedKey = org.bouncycastle.util.encoders.Base64.decode(encodedKey);
            PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
            Signature signature = Signature.getInstance("SHA256WithRSA");
            signature.initSign(privateKey);
            signature.update(content.getBytes("utf-8"));
            byte[] signed = signature.sign();
            return new String(org.bouncycastle.util.encoders.Base64.encode(signed));
        } catch (Exception var6) {
            String errorMessage = "签名遭遇异常，content=" + content + " privateKeySize=" + privateKeyPem.length() + " reason=" + var6.getMessage();
            throw new RuntimeException(errorMessage, var6);
        }
    }

    public static boolean verify(String content, String sign, String publicKeyPem) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = publicKeyPem.getBytes();
            encodedKey = org.bouncycastle.util.encoders.Base64.decode(encodedKey);
            PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
            Signature signature = Signature.getInstance("SHA256WithRSA");
            signature.initVerify(publicKey);
            signature.update(content.getBytes("utf-8"));
            return signature.verify(org.bouncycastle.util.encoders.Base64.decode(sign.getBytes()));
        } catch (Exception var7) {
            String errorMessage = "验签遭遇异常，content=" + content + " sign=" + sign + " publicKey=" + publicKeyPem + " reason=" + var7.getMessage();
            throw new RuntimeException(errorMessage, var7);
        }
    }

    public static String getTrimKey(String key) throws Exception {
        String[] datas = key.split("\n");
        String result = "";
        for (int i = 0; i < datas.length; i++) {
            if (!datas[i].startsWith("-----BEGIN") && !datas[i].startsWith("-----END")) {
                result += datas[i];
            }
        }
        return result;
    }

    // 公钥
    static String publicKey = "-----BEGIN RSA Public Key-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0pTZHm74jqa/xbYoTrVtE2bi2eMldOcdQVd/sdCpKEPUU0C/3z4qcMaqQrIU7W+nAeJ7RbSRoHF38JqyAWd2WiFIAaUrLS8ns43abtCOIn08jmfLGwlZcy0ZM7MfB5PvflARVrbfp6kBCWn3ywKt5y0PMHF68v2OhBGj88BwSFQIDAQAB-----END RSA Public Key-----";

    // 私钥
    static String privateKey = "-----BEGIN RSA Private Key-----MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBALSlNkebviOpr/FtihOtW0TZuLZ4yV05x1BV3+x0KkoQ9RTQL/fPipwxqpCshTtb6cB4ntFtJGgcXfwmrIBZ3ZaIUgBpSstLyezjdpu0I4ifTyOZ8sbCVlzLRkzsx8Hk+9+UBFWtt+nqQEJaffLAq3nLQ8wcXry/Y6EEaPzwHBIVAgMBAAECgYEAmXCXyX1lpT82HnkvxoUCuFnDBuNUDybLwNYgjOUjIqSCuDoZ9IFKOGALhDW2OXRZ+c27ASKWwQQPZOWosqEikJIswxl6GpROcS0n+IBA6XKp2T3hTajBOGOwGTptce5k3d7XSq9aBJs2A8PS5+B3qsPakO3hb5tXC8IhUyIXBkUCQQDBJlmAbzZhteV1ET14q0fbjaiBk/KWuKrhJxx/uQO4PI9/6dvo6G1tvnrlHUgGMWH0bVogfB2KAXWRzXQZULBfAkEA7205g0nLsW4wvUFNLdPvf0BGK00TNcn+i1pGTMob7kYdj/T2BlSiggqANd662sfjuAnEwVYoxv3RxCOL81RCCwJADNjHJTLAdDlL/MBbzVXfHqxKY+v6O6omu3kFfT1KEQv+I2zjkpc7CAyeUfTjoH3SXRaU4wo+ULqOHleC/FgQkwJBAOJq0DCv4MjyA3V2A56LBbm49qKMSNZdJzJxNHn5x2AVPm+cn+xsrSF8/LH0549t6JNp6X9ME1PbRDvPwdFipPECQQC2wtpEBYtctR/Azr0IPmcgu5LqrQiGkKzjnNxZS4pxVd/KyutuamhmpJv2zPaN6YoVycE3+K9mSuUpFEMWYY+L-----END RSA Private Key-----";

}
