java 小程序开发PKCS7Padding 解密方法实现,以及错误Cannot find any provider supporting AES/CBC/PKCS7Padding 解决办法

近日在对接小程序API,其中wx.getUserInfo api返回的数据encryptedData 的解密算法要求为: AES-128-CBC,数据采用PKCS#7填充。

经过一番查询,得到java自带了PKCS5Padding算法实现,但是没有PKCS7Padding(注:说的应该是jdk8之前的版本,jdk8的版本有)。需要借助BouncyCastle组件来实现。于是加了如下依赖:

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

并写了如下代码:

import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.log4j.Logger;

import com.sun.org.apache.xml.internal.security.utils.Base64;

public class DecryptUtil {
    
    private static final Logger log = Logger.getLogger(DecryptUtil.class);
    
    
    private static final String AES ="AES";
    private static final String AES_CBC_PKCS7 ="AES/CBC/PKCS7Padding";
    

    /**
     * <p>对小程序wx.getUserInfo 返回的数据进行解密</p>
     * 
     * <br>开发者如需要获取敏感数据,需要对接口返回的加密数据( encryptedData )进行对称解密。 解密算法如下:</br>
     * <li>对称解密使用的算法为 AES-128-CBC,数据采用PKCS#7填充</li>
     * <li>对称解密的目标密文为 Base64_Decode(encryptedData)</li>
     * <li>对称解密秘钥 aeskey = Base64_Decode(session_key), aeskey 是16字节。</li>
     * <li>对称解密算法初始向量 为Base64_Decode(iv),其中iv由数据接口返回</li>
     * 
     * @param encryptedData     小程序wx.getUserInfo接口返回的密文
     * @param sessionKey        会话key
     * @param iv                小程序接口返回的初始向量
     * @return {"openId":"oJ1P50LFpYwzZYaPhV1bjOrM2etY","nickName":"dimi","gender":1,"language":"zh_CN","city":"Haidian","province":"Beijing","country":"CN","avatarUrl":"http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJjUAIicI0k90UNwz7tTyWt46HrMMaxgSFPcR7Zh0MKZ4vzKibht4Sy3SrTwmYWoFSFOZOE0O1QJ0GQ/0","unionId":"orZ7js0oYCV859piu1kybaWlKGVc","watermark":{"timestamp":1493360456,"appid":"wxe87de3069cac4cf9"}}
     * @throws WechatBusinessException 
     */
    public static String decryptJsUserInfo(String encryptedData,String iv,String sessionKey) {
        
        try {
            byte[] data = Base64.decode(encryptedData);
            byte[] aseKey = Base64.decode(sessionKey);
            byte[] ivData = Base64.decode(iv);
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            
            Cipher cipher = Cipher.getInstance(AES_CBC_PKCS7);
            Key sKeySpec = new SecretKeySpec(aseKey, AES);  
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIv(ivData));// 初始化 
            
            byte[] result = cipher.doFinal(data);
            return new String(result);
        } catch (Exception e) {
            log.error("=======>小程序用户信息解密失败:"+e);
            return null;
        }  
        
    }
    
    public static AlgorithmParameters generateIv(byte[] iv) throws Exception{  
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");  
        params.init(new IvParameterSpec(iv));  
        return params;  
    }
       
    public static void main(String[] args){
        
    }
    
}

结果在本机jdk1.8的环境运行单元测试,解密成功。放到测试环境tomcat之后,解密失败,(在jdk1.7环境下运行都会失败)并报错:

java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/CBC/PKCS7Padding

一番搜索,发现stackoverflow上面也有人碰到了和我一样的问题 :

this is my code:
static {
    Security.addProvider(new BouncyCastleProvider());
}
......
final Cipher sifra = Cipher.getInstance("AES/CBC/PKCS7Padding");
Junit works fine but When I deploy my application to weblogic server I got these exception:
java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/CBC/PKCS7Padding

Can you hlp me what is wrong ?

问题下面的回答:

That's the old strange problem of different versions and missing cryptography files. I believe PKCS5Padding instead of PKCS7Padding will work. Anyway, it has something to do with Unlimited Strength Jurisdiction Policy Files which can be downloaded from Oracle ... or some other missing part or old version of Java Cryptography Extension.
同时,stackoverflow上又有人说:
PKCS7 padding and PKCS5 padding are the same thing.

于是,我把AES/CBC/PKCS7Padding 替换成AES/CBC/PKCS5Padding,也能解密成功,不报错。

这个回答

看了这么多回答之后,虽然有点懵逼,但是最终我还是解决了问题,因为我感觉是PKCS7Padding算法实现的问题,上面提到依赖了bcprov-jdk16,于是我在仓库中搜索 看是否有高版本的实现,结果发现了bcprov-ext-jdk16,名字多了个ext,我猜想是可以的,于是下载jar包反编译了一下看看,发现bcprov-jdk16的代码是他的子集。我修改了依赖包:

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

修改了这个依赖之后,运行成功。以上,供参考。

(全文完)