package org.dromara.payment.thirdPlatform.xinyujian.sign;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Random;
import java.util.UUID;

public class MD5Utils {
    /**
     * 获取MD5 随机字符串
     * @return
     * @throws Exception
     */
    public static String genKeyPair() throws Exception {
        return  UUID.randomUUID().toString().replace("-", "");
    }

    /**
     *
     * @param md5Secret 密钥
     * @param noticeStr 随机码
     * @param timestamp 事件搓
     * @return
     * @throws Exception
     */
    public static String sign(String md5Secret, String noticeStr,String  timestamp) throws Exception {
       String  password = md5Secret+noticeStr +timestamp;
        // 生成一个16位的随机数
        Random random =new Random();
        StringBuilder sBuilder =new StringBuilder(16);
        sBuilder.append(random.nextInt(99999999)).append(random.nextInt(99999999));
        int len = sBuilder.length();
        if (len <16) {
            for (int i =0; i <16 - len; i++) {
                sBuilder.append("0");
            }
        }
        // 生成最终的加密盐
        String Salt = sBuilder.toString();
        password =md5Hex(password + Salt);
        char[] cs =new char[48];
        for (int i =0; i <48; i +=3) {
            cs[i] = password.charAt(i /3 *2);
            char c = Salt.charAt(i /3);
            cs[i +1] = c;
            cs[i +2] = password.charAt(i /3 *2 +1);
        }
        return String.valueOf(cs);
    }


    public static boolean verify(String md5Secret, String noticeStr,String  timestamp, String sign) throws Exception {
        String  password = md5Secret+noticeStr +timestamp;
        char[] cs1 =new char[32];
        char[] cs2 =new char[16];
        for (int i =0; i <48; i +=3) {
            cs1[i /3 *2] = sign.charAt(i);
            cs1[i /3 *2 +1] = sign.charAt(i +2);
            cs2[i /3] = sign.charAt(i +1);
        }
        String Salt =new String(cs2);
        return md5Hex(password + Salt).equals(String.valueOf(cs1));
    }

    /**
     * 解密
     * @param encryptedData
     * @param md5Secret
     * @param noticeStr
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedData, String md5Secret, String noticeStr) throws Exception {
        String encryptedDataStart = encryptedData.replaceFirst(md5Hex(md5Secret+noticeStr),"");
        char[] charArray =  new String(Base64.decodeBase64(encryptedDataStart), StandardCharsets.UTF_8).toCharArray();
        for (int i =0; i < charArray.length; i++) {
            charArray[i] = (char) (charArray[i] ^'t');
        }
        String str = String.valueOf(charArray);
        return str;
    }

    /**
     * 加密
     * @param encryptedData
     * @param md5Secret
     * @param noticeStr
     * @return
     * @throws Exception
     */
    public static String encrypt(String encryptedData, String md5Secret, String noticeStr) throws Exception {

        char[] charArray =  encryptedData.toCharArray();
        for (int i =0; i < charArray.length; i++) {
            charArray[i] = (char) (charArray[i] ^'t');
        }
        String str = String.valueOf(charArray);
        return md5Hex(md5Secret+noticeStr)+Base64.encodeBase64String(str.getBytes(StandardCharsets.UTF_8));
    }


    @SuppressWarnings("unused")
    private static String md5Hex(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(str.getBytes());
            return new String(new Hex().encode(digest));
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.toString());
            return "";
        }
    }

    public static void main(String[] args) throws Exception {


        String ddata = "{\n" +
                "    \"sign\": \"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpQJpD7It6WGV2Q50GR7DZcdFBDNvWgShPVuBYvsWFyz4kkDDIdLTzjcr1o2tnHaJCxhiy1QTOGFqgsc5D9CETKkafDBG5Qwa6deTUjhvzwWjn01Lk1Y7uaK0f1FrxYXmHdajHk916XM4BfGjaefXAR6q1Rz+uQAlGM1SGrXYJBwIDAQAB\",\n" +
                "    \"signType\": \"RSA\",\n" +
                "    \"appid\": \"156412121\",\n" +
                "    \"timestamp\": \"1645770163620\",\n" +
                "    \"nonceStr\": \"MPzteIbCc0JiSRDWxsTQ\",\n" +
                "    \"reqMsgId\": \"394b83504cfDFDSSDSedbb6af8e9247a9d6b\",\n" +
                "    \"data\": {\n" +
                "        \"companyName\": \"北京接口科技有限公司\",\n" +
                "        \"creditCode\": \"91110108MA04EN0G0G\",\n" +
                "        \"companyAddr\": \"北京市大兴区丈八沟街道\",\n" +
                "        \"companyMobile\": \"173196655242\",\n" +
                "        \"companyEmail\": \"1564515@qq.com\",\n" +
                "        \"businessScope\": \"建筑业行业\",\n" +
                "        \"businessType\": \"土木工程建筑业\",\n" +
                "        \"serviceTypeId\": \"1\",\n" +
                "        \"registeredAssets\": \"500\",\n" +
                "        \"regdate\": \"2022-03-01\",\n" +
                "        \"bankName\": \"建设银行\",\n" +
                "        \"bankAcct\": \"622365451052525\",\n" +
                "        \"bankCode\": \"45412125620252\",\n" +
                "        \"contactName\": \"张三\",\n" +
                "        \"contactMobile\": \"17319852652\",\n" +
                "        \"referralCode\": \"1\",\n" +
                "        \"taskAuto\": \"1\",\n" +
                "        \"legalPersonName\": \"王五\",\n" +
                "        \"idNo\": \"632323190605269943\",\n" +
                "        \"idCardFace\": \"http://uat2.oss-cn-shanghai.aliyuncs.com/yinlingyun/web/file1640327997055.jpg\",\n" +
                "        \"idCardEmblem\": \"http://uat2.oss-cn-shanghai.aliyuncs.com/yinlingyun/web/file1640327997055.jpg\",\n" +
                "        \"businessLicense\": \"http://uat2.oss-cn-shanghai.aliyuncs.com/yinlingyun/web/file1640327997055.jpg\",\n" +
                "        \"accountLicense\": \"http://uat2.oss-cn-shanghai.aliyuncs.com/yinlingyun/web/file1640327997055.jpg\",\n" +
                "        \"houseNumberImg\": \"http://uat2.oss-cn-shanghai.aliyuncs.com/yinlingyun/web/file1640327997055.jpg\",\n" +
                "        \"officeSpaceImg\": \"http://uat2.oss-cn-shanghai.aliyuncs.com/yinlingyun/web/file1640327997055.jpg\",\n" +
                "        \"receptionImg\": \"http://uat2.oss-cn-shanghai.aliyuncs.com/yinlingyun/web/file1640327997055.jpg\",\n" +
                "        \"callBackUrl\": \"https://www.baidu.com\"\n" +
                "    }\n" +
                "}";

        String sa= sign("d1366134375c849d4c456191b98637520e5c548c8fa66e09","ewfwafwaefaf","156156156");
        System.out.println("签名数据==》》" + sa);
        System.out.println(verify("d1366134375c849d4c456191b98637520e5c548c8fa66e09","ewfwafwaef2af","156156156",sa));

        String ss = encrypt(ddata,"d1366134375c849d4c456191b98637520e5c548c8fa66e09","ewfwafwaefaf");
        System.out.println("==>> 加密后数据  "+ ss);
        String ss2 = decrypt(ss,"d1366134375c849d4c456191b98637520e5c548c8fa66e09","ewfwafwaefaf");
        System.out.println("==>> 解密后数据  "+ss2);


    }
}
