Exception:javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
偶发性异常:没登录时用AES/CBC/PKCS7Padding,登录后用AES/CBC/PKCS5Padding;
原因 : 微信小程序的sessionKey有一个过期时间5分钟;
解决 : 使用工具封装
import com.alibaba.fastjson.JSONObject; import org.springframework.stereotype.Component; import org.springframework.util.Base64Utils; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.AlgorithmParameterSpec; @Component public class WxMiniPhoneAnalysis { public static String getWxMiniPhone(String sessionkey, String iv, String encryptedData) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException { byte[] encrypData = Base64Utils.decodeFromString(encryptedData); byte[] ivData = Base64Utils.decodeFromString(iv); byte[] sessionKey = Base64Utils.decodeFromString(sessionkey); String resultString = null; AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData); SecretKeySpec keySpec = new SecretKeySpec(sessionKey, "AES"); try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); resultString = new String(cipher.doFinal(encrypData), "UTF-8"); } catch (Exception e) { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); resultString = new String(cipher.doFinal(encrypData), "UTF-8"); } JSONObject object = JSONObject.parseObject(resultString); // 拿到手机号码 String phone = object.getString("phoneNumber"); return phone; } }
源自: https://www.it610.com/article/1283039259715977216.htm https://developers.weixin.qq.com/community/develop/doc/0002ccdd28c1a0f852f84e3bf56400