当前位置:网站首页>微信退款回调解密req_info信息数据踩坑记录Illegal key size or default parameters

微信退款回调解密req_info信息数据踩坑记录Illegal key size or default parameters

2020-12-06 09:02:05 osc_5l7bcj86

踩坑1:微信退款涉及到证书问题

将证书文件放到resource文件夹下,

采用spring中的读取配置文件的方式读取证书文件,在本地电脑单元测试中完全没问题,后面发现是通过jenkins打包到测试服务上面由于maven插件的原因串改了证书文件,导致出现的报错解决方案

在pom文件中加入插件

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <configuration><encoding>UTF-8</encoding>
        <!-- 过滤后缀为pem、pfx,pkcs12,jks的证书文件 -->
        <nonFilteredFileExtensions>
            <nonFilteredFileExtension>pkcs12</nonFilteredFileExtension>
            <nonFilteredFileExtension>jks</nonFilteredFileExtension>
            <nonFilteredFileExtension>cer</nonFilteredFileExtension>
            <nonFilteredFileExtension>pem</nonFilteredFileExtension>
            <nonFilteredFileExtension>pfx</nonFilteredFileExtension>
        </nonFilteredFileExtensions>
    </configuration>
</plugin>

这样 问题一解决。

踩坑2 : 退款成功微信回调通过AES解密req_info信息问题

以下是微信文档中的介绍

微信退款成功后,为了网络的安全起见,微信方会在返回字段信息中通过加密 到req_info这个字段返回给我们,我们拿到数据后必须通过对其进行解密才能拿到对应的退款单号进而对我们自己业务的内部处理

微信官方给了解密文档介绍但是并没有对应的demo ,之后踩坑就开始了,以下是我的踩坑记录

private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7",
        "8", "9", "a", "b", "c", "d", "e", "f"};

//密钥算法
private static final String ALGORITHM = "AES";

//加解密算法/工作模式/填充方式
private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS7Padding";

/**
 * API密钥
 */
private static final String SERVICE_KEY = Configuration.readConfigString("service.key", "config");

/**
 * 生成key  微信key
 */
private static SecretKeySpec key = new SecretKeySpec(MD5Encode(SERVICE_KEY).toLowerCase().getBytes(), ALGORITHM);

如果只是执行上述代码的话,代码会抛出一个异常

这时我们需要在代码上面添加这句代码 这样子代码就完美执行了,但是这样的写法有个不好的地方,由于每次解密都会new 一个

BouncyCastleProvider,这个对象如果创建的多的话会导致虚虚拟机的内存溢出,这时我们做一个改进,将上述代码放到静态代码块里去

这样子写

以下是解密过程的完整代码

 private static final Logger log = Logger.getLogger(RefundNotifyDecryptionUtil.class);


    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7",
            "8", "9", "a", "b", "c", "d", "e", "f"};

    //密钥算法
    private static final String ALGORITHM = "AES";

    //加解密算法/工作模式/填充方式
    private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS7Padding";

    /**
     * API密钥
     */
    private static final String SERVICE_KEY = Configuration.readConfigString("service.key", "config");

    /**
     * 生成key  
     */
    private static SecretKeySpec key = new SecretKeySpec(MD5Encode(SERVICE_KEY).toLowerCase().getBytes(), ALGORITHM);

    static{
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null){
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        }

    }

    /**
     * AES解密
     *
     * @param base64Data
     * @return
     * @throws Exception
     */
    public static String decryptData(String base64Data) throws Exception {
        String result = "";
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
            cipher.init(Cipher.DECRYPT_MODE, key);
            result = new String(cipher.doFinal(Base64.getDecoder().decode(base64Data)));
        }catch (Exception e){
            log.info(e.getMessage());
        }

        return result;
    }


    public static void main(String[] args) throws Exception {
        //解密
        String req_info="FKV8RBK9Ws3gmFQvOBKQclyUgIkvCh7+qge1BbQ/xLTPFkIfUKbzq6XvUPLSSCvsLRVUlO/wkK7Y4RqUK0ve44tpLebYhYhqQXAGUdXrOaPiv5Ttv6codaL+6qCPIY4Vu8M2wcpXSLakofe7LvD/Hvg6Mo9Z05+MXzUX8/LwMQ0hen8ZioNrQjzGuDv9p8pT+e3oCT+PXHyshREMGSm5vm0zr9qFndWsqFwivZ23aEQQzb7CpjvzRpXLEs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zgzltFbjo7nysU+4rArqJvrGW/9r18e1St9XgG21NALqixfaSmqetOR4zLVL4/+z3CEz8cg5r+/4GUOTf3XFmLCZ/wEkRQhKRNVibG0NFfiG3KnqArMJ/dheQHCd7qL+XX/ZV6tj8RLMgL7R6hOiR03Ljyikdxq9M3K9CTYgf03pHJd3geXX1LgXrLxc1flL6NW+zD3ZayGYpr1WpLsSMG7z8W5j1pme6cRj3n2+CwSFnOnOkxaFuLKoJAJIqM3gbC0eN++vY73RKphlI4zZqg6o5s3MXI6ju1yoi/ZQ+XbTg2JttsdbU0aySernKwkt0rYMf0j/Mcvo2axgHbI3w/iTm141WxHUjkQ+ga2X1pOWdGifGhSmMP8oGaA/WD5MAsK1qXX0eFvUWS/PTauCSTWq5Cmr8loA/KL3jgvB0nyR4mfccB+tPy4Ny7kzOlr/VNeb0ULf96R0AWFWCtdt8AmujAP0DYiM5FSmYLI0XRhpSDjnEbBM8+isNE1GlAVR3NzzemwQORihScovpAktbRSN/d3N+NgTjSoVDiJvCOxCs3thX9qt9iwYbA+/X/gv8lza2FZyIzwkQxGRcYl8JWKpXzNW8EWUNVnSLdHvQttDeV3CvgP/x579RGd6whyFYS6AaI0qw7oTjCFh2EHS/VzGvFuv166ZlVIJ4MNvg79O9h63ZOSE1LzVqEsVh8fDCfM2GgJ9aUdl95Djgunit4yIZOdoigR3f/BEHKrYCEham11rYohaAXs4XAXWihsV3WD5j4G/P+txvjAwujvf4HDwzHgFsmSml013U2mUiy+v4zw==";
        String B = decryptData(req_info);
        System.out.println(B);
//        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//
//        //加密
//        String str = "<root>"+
//                "<out_refund_no><![CDATA[2531340110812300]]></out_refund_no>"+
//                "<out_trade_no><![CDATA[2531340110812100]]></out_trade_no>"+
//                "<refund_account><![CDATA[REFUND_SOURCE_RECHARGE_FUNDS]]></refund_account>"+
//                "<refund_fee><![CDATA[1]]></refund_fee>"+
//                "<refund_id><![CDATA[50000505542018011003064518841]]></refund_id>"+
//                "<refund_recv_accout><![CDATA[支付用户零钱]]></refund_recv_accout>"+
//                "<refund_request_source><![CDATA[API]]></refund_request_source>"+
//                "<refund_status><![CDATA[SUCCESS]]></refund_status>"+
//                "<settlement_refund_fee><![CDATA[1]]></settlement_refund_fee>"+
//                "<settlement_total_fee><![CDATA[1]]></settlement_total_fee>"+
//                "<success_time><![CDATA[2018-01-10 10:31:24]]></success_time>"+
//                "<total_fee><![CDATA[1]]></total_fee>"+
//                "<transaction_id><![CDATA[4200000052201801101409025381]]></transaction_id>"+
//                "</root>";
//        System.out.println(encryptData(str));
//        Map<String, String> result_map = XmlUtils.XmlToMap1("<root><out_refund_no><![CDATA[2531340110812300]]></out_refund_no><out_trade_no><![CDATA[2531340110812100]]></out_trade_no><refund_account><![CDATA[REFUND_SOURCE_RECHARGE_FUNDS]]></refund_account><refund_fee><![CDATA[1]]></refund_fee><refund_id><![CDATA[50000505542018011003064518841]]></refund_id><refund_recv_accout><![CDATA[支付用户零钱]]></refund_recv_accout><refund_request_source><![CDATA[API]]></refund_request_source><refund_status><![CDATA[SUCCESS]]></refund_status><settlement_refund_fee><![CDATA[1]]></settlement_refund_fee><settlement_total_fee><![CDATA[1]]></settlement_total_fee><success_time><![CDATA[2018-01-10 10:31:24]]></success_time><total_fee><![CDATA[1]]></total_fee><transaction_id><![CDATA[4200000052201801101409025381]]></transaction_id></root>");

//        System.out.println(result_map);
    }


    /**
     * AES加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String encryptData(String data) throws Exception {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        // 创建密码器
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
        // 初始化
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return Base64Util.encode(cipher.doFinal(data.getBytes()));
    }


    /**
     * MD5编码
     * @param origin 原始字符串
     * @return 经过MD5加密之后的结果
     */
    public static String MD5Encode(String origin) {
        String resultString = null;
        try {
            resultString = origin;
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultString;
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    /**
     * 转换字节数组为16进制字串
     * @param b 字节数组
     * @return 16进制字串
     */
    public static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (byte aB : b) {
            resultSb.append(byteToHexString(aB));
        }
        return resultSb.toString();
    }

POM文件中要加这个依赖

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-ext-jdk16</artifactId>
    <version>1.46</version>
</dependency>

通过以上方法你会发现本地代码能够正常解密成功了。但是后面坑又继续来了,把代码发布到测试服务器后法先解密并不成功 他在执行解密代码的时候会抛出异常异常信息为

Illegal key size or default parameters

接下来我们解决测试服务器的这个问题,这个问题的原因是 可能服务器的上面的jdk版本过低导致不支持key为256的解密方式 然后我们就需要修改替换jre内部的两个jar包文件

\jre\lib\security下的两个文件

将这两个文件替换掉,当然替换之前把原先两个备份一下 以防其他问题发生

注意要下载自己服务器对应版本的jar包 下面是下载地址

加解密的异常处理办法
Alibaba edited this page on 24 Dec 2019 · 5 revisions 
如果在加解密的过程中出现java.security.InvalidKeyException: Illegal key size,则需要下载一个东西:
JRE/JDK 6:http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html 
JRE/JDK 7:http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html 
JRE/JDK 8u151 之前版本:http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html 
如果安装了JRE,将两个jar文件放到$JAVA_HOME/lib/security目录下覆盖原来的文件
如果安装了JDK,将两个jar文件放到$JAVA_HOME/jre/lib/security目录下覆盖原来文件
如果是使用了工具可能内置了JRE,需要在工具引用的目录下面将两个jar文件放到/jre/lib/security目录下覆盖原来的文件
JRE/JDK 8u151 之后版本已经内置无限制权限策略文件,只需将$JAVA_HOME/jre/lib/security/java.security文件中的#crypto.policy=unlimited解除注释即可








替换完两个jar文件后注意需要刷新下环境变量

source /etc/profile

以上操作完成后 服务器重启继续一笔退款吧  发现解密代码正常了,正确解析了微信返回的加密信息了  真开心

分享完毕,如有不足还望各位大佬多多指点

 

 

 

版权声明
本文为[osc_5l7bcj86]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4346652/blog/4776584