package com.rrtx.services.common.hostenv;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Random;

public class HostCipherEnvelope {

    public HostCipherEnvelope() {
    }
    /**
     * 解密密码信封加密后字符串
     * @param certPath 证书路径【C:\\Users\\zhangzz\\text.keystore】
     * @param password 证书密码【123456】
     * @param alias 证书别名
     * @param enVal 加密后字符串
     * @return
     * 		异常返回NULL
     */
    public static String deCode(String certPath, String password,
                                String alias, String enVal) {
        // 加载私钥
        try {
            int rsaDataLength = Integer.parseInt(enVal.substring(1, 4));
            // RSA加密串
            String rsaData = enVal.substring(4, rsaDataLength + 4);
            // DES加密串
            String desData = enVal.substring(rsaDataLength + 4);

            byte[] res = RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(
                    RSAEncrypt.loadPrivateKeyByFile(certPath)), Base64.decode(rsaData));
            // 解密随机数
            String desStr = new String(DesUtils.getInstance().decrypt(Base64.decode(desData), res, null));
            // 最终解密
            String json = new String(Base64.decode(desStr), "UTF-8");
            return json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 对字符串进行密码信封式加密【JAVA证书版】
     * @param strPublicKeyPath 证书公钥路径
     * @param jsonVal 需要加密的字符串
     * @return
     */
    public static String enCode(String strPublicKeyPath, String jsonVal) {

        try {
            // 计算MAC
            String mac = MacUtils.createMac(jsonVal);

            // MAC添加到内容中
            JSONObject obj = new JSONObject(jsonVal);
            obj.put("mac", mac);

            // 获取DES加密串
            String random = getRandom(8);

            // 原始报文BASE64
            String base64 =  Base64.encode(obj.toString().getBytes());

            // DES加密
            String des = Base64.encode(
                    DesUtils.getInstance().encrypt(
                            base64.getBytes(),
                            random.getBytes(), null));

            // RSA对随机数加密
            byte[] cipherData = RSAEncrypt.encrypt(RSAEncrypt.loadPublicKeyByStr(
                    RSAEncrypt.loadPublicKeyByFile(strPublicKeyPath)),
                    random.getBytes());
            String rsa = Base64.encode(cipherData);

            // 组合
            StringBuilder sb = new StringBuilder();
            sb.append("E");
            sb.append(rsa.length());
            sb.append(rsa);
            sb.append(des);

            return sb.toString();

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            // e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成指定为数随机数
     * @param length
     * @return
     */
    private static String getRandom(int length) {
        StringBuilder str = new StringBuilder();//定义变长字符串
        Random random = new Random();
        //随机生成数字，并添加到字符串
        for(int i = 0; i < length;i++){
            str.append(random.nextInt(10));
        }
        //将字符串转换为数字并输出
        return str.toString();
    }
}
