package com.bjzc.bhzhgd.utils;


import android.util.Base64;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;


public class RSAUtils {

    /**
     * RSA算法
     */
    public static final String RSA = "RSA";
    private static final String PUBLIC_KEY = "RSAPublicKey";
    private static final String PRIVATE_KEY = "RSAPrivateKey";
    public static final int DEFAULT_KEY_SIZE = 2048;//秘钥默认长度

    //RSA最大加密明文大小 1024位是117       算法 最大加密明文大小 = 1024(bit) / 8 - 11(byte) = 117 byte  最大加密明文大小 = 2048(bit) / 8 - 11(byte) = 245 byte
    //private static final int MAX_ENCRYPT_BLOCK = 245;
    private static final int MAX_ENCRYPT_BLOCK =  (DEFAULT_KEY_SIZE / 8) - 11;
    //RSA最大解密密文大小 1024位是128        2048位是 256 依此类推
    //private static final int MAX_DECRYPT_BLOCK = 256;
    private static final int MAX_DECRYPT_BLOCK = DEFAULT_KEY_SIZE / 8;
    //java默认加密填充方式 RSA          对应安卓          RSA/None/PKCS1Padding
    //public static final String ECB_None_PKCS1_PADDING = "RSA";
    //安卓手机加密填充方式用 RSA/None/PKCS1Padding
    public static final String ECB_None_PKCS1_PADDING = "RSA/None/PKCS1Padding";

    public static final String public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnRh8MAqfpBZffouPsU3hToRZl3soo2ntYU4psQtc72QOvnprQ6Ua6UBY0WqemCJF/KxQ8p+vY7/r5eZ97Fw7Sq40PQTNKvyxFQuMGRAO8xTahSn2/79KViq7mVVLm2UAH8QaFmq7rJJbkCif3I1yiFMqzOF41ak231GF8eD62gr9+DFLiR1UKjv+/qXG4UjFQM6pa0cD1kAOsoYz0dSQlHFMbOaVf+VEWxSqFjKPiep6bYoViTlMRkdLqbUbHr/xk67C8lGqWO7wnB32T0+fYwnFWF952OJ9kov9oSnvOFXa+NwlAe7m2hZtFnW/NoBX1WxkQ6zTTTxJb8sRNft7qQIDAQAB";
    public static final String private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCdGHwwCp+kFl9+i4+xTeFOhFmXeyijae1hTimxC1zvZA6+emtDpRrpQFjRap6YIkX8rFDyn69jv+vl5n3sXDtKrjQ9BM0q/LEVC4wZEA7zFNqFKfb/v0pWKruZVUubZQAfxBoWaruskluQKJ/cjXKIUyrM4XjVqTbfUYXx4PraCv34MUuJHVQqO/7+pcbhSMVAzqlrRwPWQA6yhjPR1JCUcUxs5pV/5URbFKoWMo+J6nptihWJOUxGR0uptRsev/GTrsLyUapY7vCcHfZPT59jCcVYX3nY4n2Si/2hKe84Vdr43CUB7ubaFm0Wdb82gFfVbGRDrNNNPElvyxE1+3upAgMBAAECggEAOcphHRc7ZRSp6paStMoOoWDEyJoQ+BSms84aPjwM4y/u0JmeThM11CrMwbU0RIkPMAV//dFKpypaMIfbOREw6qctJmlWxIKS7kgCMNIcfcXlIWmvqKOJSCuOObkMCE1ef1EXu7ll8vUgY+bd8DfEs2vM6fPkDM2kFwEZgkKeZYlkFcLLy8V701seLtNzbPaqAUa44S6m0DVH7gojad8+Ni/XsdNzSrd8Y2930M8LVZoOTLrwskJaF2v/WvjM3blOtHxLqDfXfD4uRm12b1SNzPx2djlL6vNptwbpYAtPOYol8W0LxJH2AHbTrUFv/KJdyuD4NVGSnGpYtWzD7QQetQKBgQDLqfaiq0uHQerAc3M30pOZSDF8PtiBd1jdqFoOVhuADkp4LPXm54s5evEi2r3tl4x8cAvUo6WaxDlG3IFO0POLcZY+Xf2sMhwMAxiwWqLVRGirjr6QAfnmWAToqqyh8brxNti4MC3X/yudrd6x/VJ1lQ3Pooiihf4Ir74QuY7wqwKBgQDFdwbFou07bQmxCElgC5MF78Aev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f8lGLJB2DOJGKK5V69uvOLqc8zmsPSSbVlvAC+6ZHcNwKBgDWXIMmv2kUW3M+fLnvNwll2/0dsT5V/9YV7UNjCInvNckRESRa5hLojZsr++sonqNeZkD+yigypsH9e8nDvepbYJEisgweZDZ2AV5YeBjj1GWzq1zYZzW7AH4XySIM5CQexnC/Yss5UJyfUqlUMdaJGA+ELl9CxDFU6CdCRFrlrAoGAR2tVuNgX7ydPnBewCZAwVjAzdG8zQ5fZw/9n/oyMTZB96W8waFwXvzPJ4HXp5e/bzS4Mq+AmzhAstznxDq8fhC53nmc5/+AjMVtPbRDDjuIpjdFhgHSn/fPoXflerEAjbUhohJac4CUmhNFAVaz2v5Qu3+gLBtEKG/Ea7V0NDbsCgYAocw/DFV5hAyQHyVwPNtsSd/vF+iGSyJJxqBPXW36fLNzdkoZL8TNGWeuyTloZbsXBorYESTX+1522xAFr7FcQpoQRjEOAuloqc5+C03D0fSrdczbxyHQMVTvsdFbfKWaQO4EjDrZqFA50h3rhY3ZosT8IS5npZQ7ifR3B1DCfdQ==";
    public static final String public_key_local = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA/lhQRyFMV5LLJz9jFjY+ZW/79wEuujDJjy8YxlxqfST+FUUOytH46fLRd5m4s4Nj7L03hssz0H0M1pKiUzUzp6ulSC8GH2/uZzBq47agre9bW0A+Uu0IiCwfOc0J1L1UlLm/wWRGW0Sw51OHYAs99irjhxdGFOVv/mS9FzzxmBRFOwUXFD8iXyEKI8xkteyHGniKRwBYoWR32kQw7H/Mnpamo1fCrHA6Dg55CBeIEkg2oyPGKzvhkPVopJzj9zukW8w2F0iR5ll0QBl7XzGyy3EHmIsYsod3LSIh1g5A2zsscJ0ouorKGLwY1LK06a34JTkYz5p7lx6Nn6589Re8GwIDAQAB";
    public static final String private_key_local = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQD+WFBHIUxXkssnP2MWNj5lb/v3AS66MMmPLxjG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rrk584zqu6OqgE9BqHC4NwnMkd1ZmwVBC7aUB+BuVgKxb+lRXRzoYOeCYYdn4Rg0yEdSJcCTwEEwJqouAD/eCkj2KVpz2lTr1zut8w4oDwk9BYe/9R5fz9/yE+M06MAG60ys4Ac0IpfERQP8VP3a+JuTZGPvan/CSq4nGdvd/+R+aZHcQUJDXk1YzSPZFezrLIVZQe0u0HbIIfPhLHmEwCAXzhM1Ise4xC8XHOytlJw3drkNAsJN9sZ9UePLZMEkggLYgzsgSZ11tRgObA/OXPW4/fd71RO/MZmH9DLv7blCkLomTKinKDiO7MsQvjIQaDKgOVX8Db8UvVcolZLHy48c6vUbJFVXRo2ds/1MK5sgDBNGzNTX/QkPuQS+IDnh4g4edbU0tfwTzkcawHShMza+QQfcHRu5hgpurGv4CApcVWIZn49T/ElJMbSSQczbF6f08piXs8hlyUYBhFjdQJNp3Imuii2c1M10rOGn1PHR0yIay6+L1toDn6ASJksY1FCNSkzpv5utykEKf0Hq2+HX0Wi1Umdl/tndqBVXygSgi4SSu/j5iZtSnjwb1DxQKvO5LLNxxdtEJLsEpQii5LlWr7MjkcsR7zHhzzkqWIAsIbaiwuasMcRkYbAjYFcIH4mSZCTACvsTDxm+hB0GxVmGEfEgknphVm0Yqa7/NXcz9bL856ez5IemmiavfntBS8uhet3m4FYa0FolJF0YdlJa0LCXW/QQYa/PltBFx9xY9nveEp08f+DXUPzJ+0puX3qxLIMyazTfM4mWgxxPmMQOFTNwGwtNGMP6Ncbd6V4oQIDAQAB";
    public static final String private_key_mqtt = " ";

    public static byte[] decryptBASE64(String key) throws Exception {
        return Base64.decode(key, Base64.NO_WRAP);
        //return Base64.decode(key);
    }

    public static String encryptBASE64(byte[] key) throws Exception {
        return Base64.encodeToString(key, Base64.NO_WRAP);
        //return Base64.encode(key);
    }

    public static String decryptBASE64Str(String encryptString) {
        try {
            byte[] decodeByte = decryptBASE64(encryptString);
            return new String(decryptByPrivateKeyLongText(decodeByte, private_key),java.nio.charset.StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    public static String decryptBASE64StrClient(String encryptString) {
        try {
            byte[] decodeByte = decryptBASE64(encryptString);
            return new String(decryptByPrivateKeyLongText(decodeByte, private_key_client),java.nio.charset.StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String decryptBASE64StrByPublic(String encryptString) {
        try {
            byte[] decodeByte = decryptBASE64(encryptString);
            return new String(decryptByPublicKeyLongText(decodeByte, public_key),java.nio.charset.StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String decryptBASE64StrLocal(String encryptString) {
        try {
            byte[] decodeByte = decryptBASE64(encryptString);
            return new String(decryptByPrivateKeyLongText(decodeByte, private_key_local),java.nio.charset.StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String decryptBASE64StrMqtt(String encryptString) {
        try {
            byte[] decodeByte = decryptBASE64(encryptString);
            return new String(decryptByPrivateKeyLongText(decodeByte, private_key_mqtt),java.nio.charset.StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String encryptBASE64Str(String text) {
        try {
            return encryptBASE64(encryptByPublicKeyLongText(text.getBytes( java.nio.charset.StandardCharsets.UTF_8), public_key));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String encryptBASE64StrClient(String text) {
        try {
            return encryptBASE64(encryptByPublicKeyLongText(text.getBytes( java.nio.charset.StandardCharsets.UTF_8), public_key_client));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String encryptBASE64StrLocal(String text) {
        try {
            return encryptBASE64(encryptByPublicKeyLongText(text.getBytes( java.nio.charset.StandardCharsets.UTF_8), public_key_local));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String encryptBASE64StrMqtt(String text) {
        try {
            return encryptBASE64(encryptByPublicKeyLongText(text.getBytes( java.nio.charset.StandardCharsets.UTF_8), public_key_mqtt));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 解密<br>
     * 用私钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] data, String key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(ECB_None_PKCS1_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * 私钥分段解密
     * @param encryptedData
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKeyLongText(byte[] encryptedData, String privateKey) throws Exception {

        byte[] keyBytes = decryptBASE64(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(ECB_None_PKCS1_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, privateK);

        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {

                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    /**
     * 解密<br>
     * 用公钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] data, String key) throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(ECB_None_PKCS1_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }

    /**
     * 用公钥分段解密
     * @param encryptedData
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKeyLongText(byte[] encryptedData, String publicKey) throws Exception {

        byte[] keyBytes = decryptBASE64(publicKey);

        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);

        KeyFactory keyFactory = KeyFactory.getInstance(RSA);

        Key publicK = keyFactory.generatePublic(x509KeySpec);

        Cipher cipher = Cipher.getInstance(ECB_None_PKCS1_PADDING);

        cipher.init(Cipher.DECRYPT_MODE, publicK);

        int inputLen = encryptedData.length;

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int offSet = 0;

        byte[] cache;

        int i = 0;

        // 对数据分段解密

        while (inputLen - offSet > 0) {

            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {

                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);

            } else {

                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);

            }

            out.write(cache, 0, cache.length);

            i++;

            offSet = i * MAX_DECRYPT_BLOCK;

        }

        byte[] decryptedData = out.toByteArray();

        out.close();

        return decryptedData;

    }


    /**
     * 加密<br>
     * 用公钥加密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception {
        // 对公钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(ECB_None_PKCS1_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }

    /**
     * 用公钥分段加密
     * @param data
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKeyLongText(byte[] data, String publicKey) throws Exception {

        byte[] keyBytes = decryptBASE64(publicKey);

        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);

        KeyFactory keyFactory = KeyFactory.getInstance(RSA);

        Key publicK = keyFactory.generatePublic(x509KeySpec);

        // 对数据加密

        Cipher cipher = Cipher.getInstance(ECB_None_PKCS1_PADDING);

        cipher.init(Cipher.ENCRYPT_MODE, publicK);

        int inputLen = data.length;

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int offSet = 0;

        byte[] cache;

        int i = 0;

        // 对数据分段加密

        while (inputLen - offSet > 0) {

            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {

                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);

            } else {

                cache = cipher.doFinal(data, offSet, inputLen - offSet);

            }

            out.write(cache, 0, cache.length);

            i++;

            offSet = i * MAX_ENCRYPT_BLOCK;

        }

        byte[] encryptedData = out.toByteArray();

        out.close();

        return encryptedData;

    }

    /**
     * 加密<br>
     * 用私钥加密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, String key) throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(ECB_None_PKCS1_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * 用私钥分段加密
     * @param data
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKeyLongText(byte[] data, String privateKey) throws Exception {

        byte[] keyBytes = decryptBASE64(privateKey);

        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

        KeyFactory keyFactory = KeyFactory.getInstance(RSA);

        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);

        Cipher cipher = Cipher.getInstance(ECB_None_PKCS1_PADDING);

        cipher.init(Cipher.ENCRYPT_MODE, privateK);

        int inputLen = data.length;

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int offSet = 0;

        byte[] cache;

        int i = 0;

        // 对数据分段加密

        while (inputLen - offSet > 0) {

            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {

                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);

            } else {

                cache = cipher.doFinal(data, offSet, inputLen - offSet);

            }

            out.write(cache, 0, cache.length);

            i++;

            offSet = i * MAX_ENCRYPT_BLOCK;

        }

        byte[] encryptedData = out.toByteArray();

        out.close();

        return encryptedData;

    }

    /**
     * 取得私钥
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map<String, Object> keyMap)
            throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);

        return encryptBASE64(key.getEncoded());
    }

    /**
     * 取得公钥
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map<String, Object> keyMap)
            throws Exception {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return encryptBASE64(key.getEncoded());
    }

    /**
     * 初始化密钥
     *
     * @return
     * @throws Exception
     */
    public static Map<String, Object> initKey() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator
                .getInstance(RSA);
        keyPairGen.initialize(DEFAULT_KEY_SIZE);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        // 私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<String, Object>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    public static void rsa() {
        try {
            Map<String, Object> key = RSAUtils.initKey();
            String publicKey = RSAUtils.getPublicKey(key);
            String privateKey = RSAUtils.getPrivateKey(key);
            String signbypub = RSAUtils.encryptBASE64(RSAUtils.encryptByPublicKey("wenfei".getBytes(), RSAUtils.public_key));
            byte[] decodeByte = RSAUtils.decryptBASE64(signbypub);
            String ecodeStr = new String(RSAUtils.decryptByPrivateKey(decodeByte, RSAUtils.private_key));
            Log.i("app", "-----------公钥------------");
            Log.i("app", publicKey);
            Log.i("app", "-----------私钥------------");
            Log.i("app", privateKey);
            Log.i("app", "-----------公钥加密------------");
            Log.i("app", signbypub);
            Log.i("app", "-----------私钥解密------------");
            Log.i("app", ecodeStr);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            Map<String, Object> key = RSAUtils.initKey();
            String publicKey = RSAUtils.getPublicKey(key);
            String privateKey = RSAUtils.getPrivateKey(key);
            String signbypub = RSAUtils.encryptBASE64(RSAUtils.encryptByPublicKey("wenfei".getBytes(), RSAUtils.public_key));
            byte[] decodeByte = RSAUtils.decryptBASE64(signbypub);
            String ecodeStr = new String(RSAUtils.decryptByPrivateKey(decodeByte, RSAUtils.private_key));
            Log.i("app", "-----------公钥------------");
            Log.i("app", publicKey);
            Log.i("app", "-----------私钥------------");
            Log.i("app", privateKey);
            Log.i("app", "-----------公钥加密------------");
            Log.i("app", signbypub);
            Log.i("app", "-----------私钥解密------------");
            Log.i("app", ecodeStr);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}