微信小程序加密数据解密算法 java
获取用户头像、昵称、手机号等授权信息,需解密
java 微信小程序加密数据解密算法
1 /** 2 * 加密数据解密 3 * 4 * @param encryptedData 5 * @param sessionKey 6 * @param iv 7 * @return 8 */ 9 private String decrypt(String encryptedData, String sessionKey, String iv) { 10 String result = ""; 11 try { 12 byte[] resultByte = AES.decrypt(Base64.decodeBase64(encryptedData), 13 Base64.decodeBase64(sessionKey), 14 Base64.decodeBase64(iv)); 15 if (null != resultByte && resultByte.length > 0) { 16 result = new String(resultByte, "UTF-8"); 17 } 18 } catch (Exception e) { 19 e.printStackTrace(); 20 } 21 return result; 22 }
AES 解密工具类
1 import org.bouncycastle.jce.provider.BouncyCastleProvider; 2 3 import javax.crypto.BadPaddingException; 4 import javax.crypto.Cipher; 5 import javax.crypto.IllegalBlockSizeException; 6 import javax.crypto.NoSuchPaddingException; 7 import javax.crypto.spec.IvParameterSpec; 8 import javax.crypto.spec.SecretKeySpec; 9 import java.security.*; 10 11 public class AES { 12 public static boolean initialized = false; 13 14 /** 15 * AES解密 16 * 17 * @param content 18 * 密文 19 * @return 20 * @throws InvalidAlgorithmParameterException 21 * @throws NoSuchProviderException 22 */ 23 public static byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException { 24 initialize(); 25 try { 26 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); 27 Key sKeySpec = new SecretKeySpec(keyByte, "AES"); 28 cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIv(ivByte));// 初始化 29 byte[] result = cipher.doFinal(content); 30 return result; 31 } catch (NoSuchAlgorithmException e) { 32 e.printStackTrace(); 33 } catch (NoSuchPaddingException e) { 34 e.printStackTrace(); 35 } catch (InvalidKeyException e) { 36 e.printStackTrace(); 37 } catch (IllegalBlockSizeException e) { 38 e.printStackTrace(); 39 } catch (BadPaddingException e) { 40 e.printStackTrace(); 41 } catch (NoSuchProviderException e) { 42 // TODO Auto-generated catch block 43 e.printStackTrace(); 44 } catch (Exception e) { 45 // TODO Auto-generated catch block 46 e.printStackTrace(); 47 } 48 return null; 49 } 50 51 public static void initialize() { 52 if (initialized) { 53 return; 54 } 55 Security.addProvider(new BouncyCastleProvider()); 56 initialized = true; 57 } 58 59 // 生成iv 60 public static AlgorithmParameters generateIv(byte[] iv) throws Exception { 61 AlgorithmParameters params = AlgorithmParameters.getInstance("AES"); 62 params.init(new IvParameterSpec(iv)); 63 return params; 64 } 65 }
以下情况,有可能导致解密失效:
1、短时间的多次 wx.login
2、授权回调里,又再次 wx.login
也就是,没事不要瞎调用 wx.login
docker容器,报 java.lang.NoClassDefFoundError: org/bouncycastle/ 错误,看这>>