背景:项目中使用微信小程序获取用户微信步数时经常失败。查看log中时发现了大量的微信步数解密失败的日志。
解析微信步数失败,更换解密模式重试
javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
at com.sun.crypto.provider.CipherCore.unpad(CipherCore.java:975)
at com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1056)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2168)
at com.ancient.kuafu.service.PedometerWechatImp.decryptionStepInfo(PedometerWechatImp.java:178)
at com.ancient.kuafu.service.PedometerWechatImp$$FastClassBySpringCGLIB$$247dd861.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:779)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692)
at com.ancient.kuafu.service.PedometerWechatImp$$EnhancerBySpringCGLIB$$dd48042b.decryptionStepInfo(<generated>)
at com.ancient.kuafu.controller.CountUserController.leijiSteps(CountUserController.java:59)
at sun.reflect.GeneratedMethodAccessor418.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
原因:微信的用户数据使用的时AES/CBC 模式进行的数据加密(对改加密算法不了解的同学可以先看一下AES加密算法的实现原理)。经排查发现前端在微信登录code失效后,从新获取微信code后,没有重新获取步数加密的信息,和初始化向量。导致解密时报密钥有问题的错误。
总结:微信加密的数据,需要登录code,加密数据,初始化向量三者配置使用。