package com.crm.rely.backend.util;

import org.apache.commons.lang3.ArrayUtils;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;


/**
 * @program: crm-backend
 * @description:
 * @author: houn
 * @create: 2019-07-29 16:18
 */
public class RSAUtil {
    //非对称密钥算法
    private static final String KEY_ALGORITHM = "RSA";
    //密钥长度，在512到65536位之间，建议不要太长，否则速度很慢，生成的加密数据很长
    private static final int KEY_SIZE = 512;
    //字符编码
    private static final String CHARSET = "UTF-8";

    /**
     * 签名算法
     */
    public static final String SIGNATURE_ALGORITHM_SHA1 = "SHA1withRSA";

    /**
     * 生成密钥对
     *
     * @return KeyPair 密钥对
     */
    public static KeyPair getKeyPair() throws Exception {
        return getKeyPair(null);
    }

    /**
     * 生成密钥对
     *
     * @param password 生成密钥对的密码
     * @return
     * @throws Exception
     */
    public static KeyPair getKeyPair(String password) throws Exception {
        //实例化密钥生成器
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        //初始化密钥生成器
        if (password == null) {
            keyPairGenerator.initialize(KEY_SIZE);
        } else {
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(password.getBytes(CHARSET));
            keyPairGenerator.initialize(KEY_SIZE, secureRandom);
        }
        //生成密钥对
        return keyPairGenerator.generateKeyPair();
    }

    /**
     * 取得私钥
     *
     * @param keyPair 密钥对
     * @return byte[] 私钥
     */
    public static byte[] getPrivateKeyBytes(KeyPair keyPair) {
        return keyPair.getPrivate().getEncoded();
    }

    /**
     * 取得Base64编码的私钥
     *
     * @param keyPair 密钥对
     * @return String Base64编码的私钥
     */
    public static String getPrivateKey(KeyPair keyPair) {
        return Base64.getEncoder().encodeToString(getPrivateKeyBytes(keyPair));
    }

    /**
     * 取得公钥
     *
     * @param keyPair 密钥对
     * @return byte[] 公钥
     */
    public static byte[] getPublicKeyBytes(KeyPair keyPair) {
        return keyPair.getPublic().getEncoded();
    }

    /**
     * 取得Base64编码的公钥
     *
     * @param keyPair 密钥对
     * @return String Base64编码的公钥
     */
    public static String getPublicKey(KeyPair keyPair) {
        return Base64.getEncoder().encodeToString(getPublicKeyBytes(keyPair));
    }

    /**
     * 私钥加密
     *
     * @param data       待加密数据
     * @param privateKey 私钥字节数组
     * @return byte[] 加密数据
     */
    public static byte[] encryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception {
        //实例化密钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //生成私钥
        PrivateKey key = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKey));
        //数据加密
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] enBytes = null;
        for (int i = 0; i < data.length; i += 32) {
            // 注意要使用2的倍数，否则会出现加密后的内容再解密时为乱码
            byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + 32));
            enBytes = ArrayUtils.addAll(enBytes, doFinal);
        }
        return enBytes;
    }

    /**
     * 私钥加密
     *
     * @param data       待加密数据
     * @param privateKey Base64编码的私钥
     * @return String Base64编码的加密数据
     */
    public static String encryptByPrivateKey(String data, String privateKey) throws Exception {
        byte[] key = Base64.getDecoder().decode(privateKey);
        return Base64.getEncoder().encodeToString(encryptByPrivateKey(data.getBytes(CHARSET), key));
    }

    /**
     * 公钥加密
     *
     * @param data      待加密数据
     * @param publicKey 公钥字节数组
     * @return byte[] 加密数据
     */
    public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
        //实例化密钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //生成公钥
        PublicKey key = keyFactory.generatePublic(new X509EncodedKeySpec(publicKey));
        //数据加密
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] enBytes = null;
        for (int i = 0; i < data.length; i += 32) {
            // 注意要使用2的倍数，否则会出现加密后的内容再解密时为乱码
            byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + 32));
            enBytes = ArrayUtils.addAll(enBytes, doFinal);
        }
        return enBytes;
    }

    /**
     * 公钥加密
     *
     * @param data      待加密数据
     * @param publicKey Base64编码的公钥
     * @return String Base64编码的加密数据
     */
    public static String encryptByPublicKey(String data, String publicKey) throws Exception {
        byte[] key = Base64.getDecoder().decode(publicKey);
        return Base64.getEncoder().encodeToString(encryptByPublicKey(data.getBytes(CHARSET), key));
    }

    /**
     * 私钥解密
     *
     * @param data       待解密数据
     * @param privateKey 私钥字节数组
     * @return byte[] 解密数据
     */
    public static byte[] decryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception {
        //实例化密钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //生成私钥
        PrivateKey key = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKey));
        //数据解密
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] enBytes = null;
        for (int i = 0; i < data.length; i += 64) {
            byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + 64));

            enBytes = ArrayUtils.addAll(enBytes, doFinal);
        }

        return enBytes;
    }

    /**
     * 私钥解密
     *
     * @param data       Base64编码的待解密数据
     * @param privateKey Base64编码的私钥
     * @return String 解密数据
     */
    public static String decryptByPrivateKey(String data, String privateKey) throws Exception {
        byte[] key = Base64.getDecoder().decode(privateKey);
        return new String(decryptByPrivateKey(Base64.getDecoder().decode(data), key), CHARSET);
    }

    /**
     * 私钥解密
     *
     * @param data       待解密数据
     * @param privateKey Base64编码的私钥
     * @return String 解密数据
     */
    public static String decryptByPrivateKey(byte[] data, String privateKey) throws Exception {
        byte[] key = Base64.getDecoder().decode(privateKey);
        return new String(decryptByPrivateKey(data, key), CHARSET);
    }

    /**
     * 私钥解密
     *
     * @param data       Base64编码的待解密数据
     * @param privateKey 私钥
     * @return String 解密数据
     */
    public static String decryptByPrivateKey(String data, byte[] privateKey) throws Exception {

        return new String(decryptByPrivateKey(Base64.getDecoder().decode(data), privateKey), CHARSET);
    }

    /**
     * 公钥解密
     *
     * @param data      待解密数据
     * @param publicKey 公钥字节数组
     * @return byte[] 解密数据
     */
    public static byte[] decryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
        //实例化密钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //产生公钥
        PublicKey key = keyFactory.generatePublic(new X509EncodedKeySpec(publicKey));
        //数据解密
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] enBytes = null;
        for (int i = 0; i < data.length; i += 64) {
            byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + 64));

            enBytes = ArrayUtils.addAll(enBytes, doFinal);
        }

        return enBytes;
    }

    /**
     * 公钥解密
     *
     * @param data      待解密数据
     * @param publicKey Base64编码的公钥
     * @return string 解密数据
     * @throws Exception
     */
    public static String decryptByPublicKey(String data, String publicKey) throws Exception {
        byte[] key = Base64.getDecoder().decode(publicKey);
        return new String(decryptByPublicKey(Base64.getDecoder().decode(data), key), CHARSET);
    }

    /**
     * 公钥解密
     *
     * @param data      Base64编码的待解密数据
     * @param publicKey Base64编码的公钥
     * @return string 解密数据
     * @throws Exception
     */
    public static String decryptByPublicKey(byte[] data, String publicKey) throws Exception {
        byte[] key = Base64.getDecoder().decode(publicKey);
        return new String(decryptByPublicKey(data, key), CHARSET);
    }

    /**
     * 公钥解密
     *
     * @param data      待加密数据
     * @param publicKey 公钥字节数组
     * @return string 解密数据
     * @throws Exception
     */
    public static String decryptByPublicKey(String data, byte[] publicKey) throws Exception {

        return new String(decryptByPublicKey(Base64.getDecoder().decode(data), publicKey), CHARSET);
    }

    /**
     * RSA公钥转换
     * @param publicKeyStr 公钥字符串
     * @return 公钥
     * @throws
     */
    public static PublicKey parsePublicKey(String publicKeyStr) throws Exception {
        PublicKey publicKey = null;
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            byte[] encodedKey = Base64.getDecoder().decode(publicKeyStr.getBytes(StandardCharsets.UTF_8));
            publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
        } catch (NoSuchAlgorithmException e) {
        }
        return publicKey;
    }

    /**
     * RSA私钥转换
     *
     * @param privateKeyStr 私钥字符串
     * @return 私钥
     * @throws
     */
    public static PrivateKey parsePrivateKey(String privateKeyStr) throws Exception {
        PrivateKey privateKey = null;
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            byte[] encodedKey = Base64.getDecoder().decode(privateKeyStr.getBytes(StandardCharsets.UTF_8));
            privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
         } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return privateKey;
    }

    /**
     * 签名(使用商户私钥)
     * @param data 待签名数据
     * @param privateKey 私钥
     * @return
     */
    public static String signSHA1(String data, String privateKey) throws Exception {
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM_SHA1);
        signature.initSign(parsePrivateKey(privateKey));
        signature.update(data.getBytes(CHARSET));
        return new String(org.apache.commons.codec.binary.Base64.encodeBase64(signature.sign()));
    }

    /**
     * 验签(使用平台公钥)
     * @param data
     * @return
     * @throws Exception
     */
    public static boolean verify(String data,String sign,String publicKey) throws Exception {
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM_SHA1);
        signature.initVerify(parsePublicKey(publicKey));
        signature.update(data.getBytes(CHARSET));
        return signature.verify(org.apache.commons.codec.binary.Base64.decodeBase64(sign.getBytes("UTF-8")));
    }

    /**
     * 测试加解密方法
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
//        //生成密钥对，一般生成之后可以放到配置文件中
//        KeyPair keyPair = RSAUtil.getKeyPair();
//
//        //公钥
//        String publicKey = RSAUtil.getPublicKey(keyPair);
//        //私钥
//        String privateKey = RSAUtil.getPrivateKey(keyPair);
//
//        System.out.println("公钥：\n" + publicKey);
//        System.out.println("私钥：\n" + privateKey);
//
//        String data = "RSA 加解密测试!RSA 加解密测试!RSA 加解密测试!RSA 加解密测试!RSA 加解密测试!RSA 加解密测试!RSA 加解密测试!RSA 加解密测试!RSA
//        加解密测试!RSA 加解密测试!RSA 加解密测试!RSA 加解密测试!RSA 加解密测试!RSA 加解密测试!RSA 加解密测试!RSA 加解密测试!RSA 加解密测试!";
//        {
//            System.out.println("\n===========私钥加密，公钥解密==============");
//            String s1 = RSAUtil.encryptByPrivateKey(data, privateKey);
//            System.out.println("加密后的数据:" + s1);
//            String s2 = RSAUtil.decryptByPublicKey(s1, publicKey);
//            System.out.println("解密后的数据:" + s2 + "\n\n");
//        }
//
//        {
//            System.out.println("\n===========公钥加密，私钥解密==============");
//            String s1 = RSAUtil.encryptByPublicKey(data, publicKey);
//            System.out.println("加密后的数据:" + s1);
//            String s2 = RSAUtil.decryptByPrivateKey(s1, privateKey);
//            System.out.println("解密后的数据:" + s2 + "\n\n");
//        }

        {

            String signString = "amount=1400&buyerId=76534&buyerName=张三&merId=168038&notifyUrl=https://my.icitywealth" +
                    ".com/PayAnx/Notify&payType=00&seqId=CWH20240418134118591_182288&transDate=20240418&transTime" +
                    "=134119&version=2.0";
            String privateKey1 =
                    "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKfDHPP9P3QVyjvq3I7Daa3bSWsk4wYbviMWFw0QIwUnBXp37LwDAMp/Ai2WBPwXRRBC8foKRhxDZJ1GRZIZ+yILjbwNfkN6BiEhVe8GH+LfePzlcxJaI3Zz2yOKja7Tni2+8p62bZiK1ntb2OhXT0Dibsd4u5VWauf/+UK4HofZAgMBAAECgYBv/IsDRHZrI3CQdsMseb291Lg50bHKjhJqkYBps+/srJO3oP5isw6AHjByBcbmERKFPGsTInCSxVoQsqwWT0mX57TTp8S6zXDTxTXr6wBDq9vlJJsqOHdCUAUAGnW3/5roEl5JDIltU7/Vek/I4FZHmPsqzCp2kEM6XwntWBmFQQJBANF0C2A6q1IbYDt53ZgP2JFqWJZqDR+Oz5+4X+8nLOk0hokPtmIcYn699n21Y9TorvC5/SZqPX2Fr2sUGNk7bj0CQQDNCzp+Et6q+UgzWX+Zqx4zMFF+Gr8Ity8Pc94tSMQ4Jy4GrzqQdUshP6vf0Q9tjNcvjd26zFpt8Hbak07LcVXNAkEA0WLc7Ho6Qn6zmUGe0SEmM1jI7rVeISo3TUiYPxA+yXOE+wgGH9aYcHOfMtRe1L04Bdcox3p1tkIqtzUEEkZjUQJBAKyBct+Yvo83lN/mvyyow4qrbxRaKjiJ7WThxZ1xp+vaQqXLDMl2dRPu/ooZ2BIBuRTAFTjQLpBqC4SPBG6y1k0CQEfU5tPLGJh+UhxeivUh0EyMaPIKhkGfcgYTpVbAV68UK9JXHRB5ZkNHlUlNwZDcOiBdBTMvtnRwofv17crdmdE=";
            String s1 = RSAUtil.encryptByPrivateKey(signString, privateKey1);
            System.out.println("加密后的数据:" + s1);
        }
    }
}