package com.upyuns.platform.rs.website.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.Map;

public class LoginDigestUtil {
    public static final String CHARSET = "utf-8";
    public static final String ENCRYPTION_ALGORITHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    public static void main(String[] args) throws Exception {
        // 获取公私密钥对
        KeyPair keyPair = getKeyPair(1024);
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();
        String pbcKey = getPublicKey(keyPair);
        System.out.println(pbcKey);
        String pvtKey = getPrivateKey(keyPair);
        System.out.println(pvtKey);

        String data = "123456";
        String ciphertext = encryptByPublicKey(data, pbcKey);
        System.out.println("ciphertext = " + ciphertext);
        String original = decryptByPrivateKey(ciphertext, pvtKey);
        System.out.println("original text = " + original);

        Long timelong = new Date().getTime();
        String uuid = timelong+ "";
        String time = (timelong + 1L) + "";

        // RSA签名
        pvtKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALcPs3K2jRrdYSWFvsgMOogWgwa15kmEUC3AxlL4OwTOUFcxakZXKJdfBERK2Amz1ctf7RBGCq8WeAM07vcGSa9Ipp511w6YSezQIei748gN368o7lLfeXXE2ht8zLfCF05soLHtigjCYgM3pZPPfwRste+SV3G/Up8Ij/eW3hi1AgMBAAECgYANXw05fNITu0XkSr+jtxjzZcmOTO0UQ6DjpqgV2WHeOP+vTsG3f5hMbjlOj7T2CHe+UjRrsuIG5fpAKbamvoPVNQWT3C+PjA0xQqWU/LOnoIPfTI/JUYBkKtP3NAjib5bI61pqGJ0tLW4C6w1y3F0Qx0X8vyEnE9gLVuZ9c3+DwQJBAPGQc4kahnyKOQ0UO2+G0EjcuzLFkiZ6R83w5gBpe4i2EFGNzIrq8O3JxTI8n9nk+3CEXkvj6sEauRw/NyEsAtECQQDCAD95GBnADDZ4nshlhF0aA98+B37t2Uf/I7ZeRlT1jsdgeHsEAQXUUTRkQriAb1oX6GiEwjxx1OZ1+jSPvcilAkAhB5BUodTbuIaefDK4SCW4oL3T7mHScwvYY+T/D209vy8yB4J9SCyTRvB4swNkZsPemarPE6Xoq3++FgKyvXLRAkEAmCEZpRwBFVh+XpglDXZ+i6f9p+a44ktA6hJXMBZ3CRitwDi6PqmOqLAFJZoslIq9W4Ikc/bc72bEUj+ieBWbAQJAOGzhE6H3mR+XIM7S5mkZvjswtyGApjYuIq1Sm7b0aQm1L4IN9pXaHtQOhEnigPTMAexu/GX4LDyWlKZIcv8M+A==";
        original = "appKey=guangdong&uid="+uuid+"&timestamp="+time;
        String sign = sign(original, pvtKey);

        System.out.println(uuid);
        System.out.println(time);
        System.out.println(sign);

        HttpRequest httpRequest = HttpRequest.post("https://smartplanting.cm-agri.com:442/plant-service/openApi/order");
        Map<String, String> headers = CollUtil.newHashMap();
        headers.put("appKey", "guangdong");
        headers.put("uid", uuid);
        headers.put("timestamp", time);
        headers.put("sign", sign);

        Map<String, Object> form = CollUtil.newHashMap();
        headers.put("moduleCode", "landResource");
        headers.put("regionCode", "440200");
        headers.put("startTime", "2024-01-01");
        headers.put("endTime", "2024-06-01");

        httpRequest.addHeaders(headers);
        httpRequest.form(form);
        String body = httpRequest.execute().body();

//        // RSA验签
//        boolean result = verify(original, pbcKey, sign);
//        System.out.print("验签结果:" + result);
    }

    /**
     * 生成密钥 keyLength 1024
     */
    public static KeyPair getKeyPair(int keyLength) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(keyLength);
        return keyPairGenerator.generateKeyPair();
    }


    /**
     * 获取公钥
     *
     * @param keyPair 密钥对
     * @return
     */
    public static String getPublicKey(KeyPair keyPair) throws Exception {
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        return Base64Util.encryptBASE64(publicKey.getEncoded());
    }

    /**
     * 公钥字符串转PublicKey实例
     *
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        byte[] publicKeyBytes = Base64Util.decryptBASE64(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }


    /**
     * 获取私钥字符串
     *
     * @param keyPair
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(KeyPair keyPair) throws Exception {
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        return Base64Util.encryptBASE64(privateKey.getEncoded());
    }

    /**
     * 私钥字符串转PrivateKey实例
     *
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        byte[] privateKeyBytes = Base64Util.decryptBASE64(privateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 公钥加密————RSA
     */
    public static byte[] encryptByPublicKey(byte[] content, String publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey));
        return cipher.doFinal(content);
    }

    /**
     * 公钥加密————RSA
     */
    public static String encryptByPublicKey(String content, String publicKey) throws Exception {
        return new String(Base64.getEncoder().encode(encryptByPublicKey(content.getBytes(), publicKey)), CHARSET);
    }


    /**
     * 私钥解密
     */
    public static byte[] decryptByPrivateKey(byte[] content, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(content);
    }


    /**
     * 私钥解密
     */
    public static String decryptByPrivateKey(String content, String privateKey) throws Exception {
        return new String(decryptByPrivateKey(Base64.getDecoder().decode(content), getPrivateKey(privateKey)), CHARSET);
    }

    /**
     * 私钥加密
     */
    public static byte[] encryptByPrivateKey(byte[] content, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(content);
    }

    public static String encryptByPrivateKey(String content, String privateKey) throws Exception {
        return new String(Base64.getEncoder().encode(encryptByPrivateKey(content.getBytes(), getPrivateKey(privateKey))), CHARSET);
    }


    /**
     * 公钥解密—RSA
     *
     * @param content
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static byte[] decrypByPublicKey(byte[] content, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return cipher.doFinal(content);
    }

    /**
     * 公钥解密—RSA
     *
     * @param content
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static String decrypByPublicKey(String content, String publicKey) throws Exception {
        return new String(decrypByPublicKey(Base64.getDecoder().decode(content), getPublicKey(publicKey)), CHARSET);

    }

    /**
     * 签名
     *
     * @param content
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] sign(byte[] content, PrivateKey privateKey) throws Exception {
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateKey);
        signature.update(content);
        return signature.sign();
    }

    /**
     * 私钥签名
     *
     * @param content
     * @return
     * @throws Exception
     */
    public static String sign(String content, String privateKey) throws Exception {
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(getPrivateKey(privateKey));
        signature.update(content.getBytes());
        return new String(Base64.getEncoder().encode(signature.sign()), CHARSET);
    }

    /**
     * 校验签名
     *
     * @param content   数据内容
     * @param publicKey 公钥
     * @param sign      签名
     * @return
     * @throws Exception
     */
    public static boolean verify(byte[] content, String publicKey, String sign) throws Exception {

        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(getPublicKey(publicKey));
        signature.update(content);

        // 验证签名是否正常
        return signature.verify(Base64.getDecoder().decode(sign));
    }

    /**
     * 公钥校验签名
     *
     * @param content   数据内容
     * @param publicKey 公钥
     * @param sign      签名
     * @return
     * @throws Exception
     */
    public static boolean verify(String content, String publicKey, String sign) throws Exception {
        return verify(content.getBytes(), publicKey, sign);
    }

    public static class Base64Util {

        /**
         * Base64加密
         */
        public static String encryptBASE64(byte[] key) {
            return (new BASE64Encoder()).encodeBuffer(key);
        }

        /**
         * Base64解密
         */
        public static byte[] decryptBASE64(String key) throws Exception {
            return (new BASE64Decoder()).decodeBuffer(key);
        }

    }
}