1.场景
在做微信支付退款通知接口时,微信对通知的内容做了加密,并且指定用 AES256 解密,官方指定的解密方式如下:
2.导包
<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on --> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.60</version> </dependency> <!-- https://mvnrepository.com/artifact/org.jasypt/jasypt --> <dependency> <groupId>org.jasypt</groupId> <artifactId>jasypt</artifactId> <version>1.9.3</version> </dependency>
3.解密
说明:方法中参数 reqInfo 就是退款结果通知接口中的 req_info 字段值
private String descrypt(String reqInfo) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { byte[] reqInfoB = Base64.decodeBase64(reqInfo); String key_ = DigestUtils.md5Hex(WXPayConfig.getInstance().getKey()).toLowerCase(); if (Security.getProvider("BC") == null){ Security.addProvider(new BouncyCastleProvider()); } Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC"); SecretKeySpec secretKeySpec = new SecretKeySpec(key_.getBytes(), "AES"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); return new String(cipher.doFinal(reqInfoB)); }
4.结果
5.上述过程之后在win本地运行没问题了,但是放到 linux 之后报错如下:
java.security.InvalidKeyException: Illegal key size or default parameters
最终还是按网友的方法解决:替换jre包:local_policy.jar,US_export_policy.jar
5.1.下载
需要注意的是:替换的jar包版本需要与jre版本一致,各个版本包连接
jdk8:http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
jdk7:http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
jdk6:http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html
jdk5:http://download.csdn.net/detail/scs2043/4237335
5.2.替换路径
%JAVE_HOME%jrelibsecurity
6.参考
解密方式:https://blog.csdn.net/qq_25958497/article/details/87937020
报错解决(报错内容“No such provider: BC”):https://www.cnblogs.com/wswang/p/7718150.html
替换包参考:https://blog.csdn.net/tomatocc/article/details/85096911