通过 java 实现微信小程序用户加密数据的解密
环境:
window 或 linux
jdk1.7
所需依赖:
commons-codec
commons-codec
1.12
org.bouncycastle
bcprov-jdk15on
1.57
代码实现:
package com.test.utils;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
public class DecryptionUtils {
public static String decode(String sessionKey,String encryptedData,String iv)
throws Exception{
byte[] encrypData = Base64.decodeBase64(encryptedData);
byte[] ivData = Base64.decodeBase64(iv);
byte[] sessionKeyB = Base64.decodeBase64(sessionKey);
Security.addProvider(new BouncyCastleProvider());
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
SecretKeySpec keySpec = new SecretKeySpec(sessionKeyB, "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] doFinal = cipher.doFinal(encrypData);
return new String(doFinal);
}
}
注意
如果解密报错 javax.crypto.BadPaddingException: pad block corrupted 极有可能是因为sessionKey或encryptedData或iv不匹配