解析微信小程序手机号异常 Exception:javax.crypto.BadPaddingException: Given final block not properly padded. S...

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;

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.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;

/**

  • @Description TODO
  • @Author jizhuolin
  • @Date 2018/9/28
    /
    public class WxMiniappUtils {
    /
    • 解密用户手机号算法

    • @param sessionkey 小程序登录sessionKey

    • @param iv 向量

    • @param encryptedData

    • @return

    • @throws NoSuchPaddingException

    • @throws NoSuchAlgorithmException

    • @throws InvalidAlgorithmParameterException

    • @throws InvalidKeyException

    • @throws BadPaddingException

    • @throws IllegalBlockSizeException
      */
      public static byte[] decrypt(byte[] sessionkey, byte[] iv, byte[] encryptedData)
      throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
      InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
      AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);

      byte[] data = null;
      try {
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      SecretKeySpec keySpec = new SecretKeySpec(sessionkey, "AES");
      cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
      data = cipher.doFinal(encryptedData);
      }catch (Exception e){
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
      SecretKeySpec keySpec = new SecretKeySpec(sessionkey, "AES");
      cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
      data = cipher.doFinal(encryptedData);
      }

      return data;
      }
      }

你可能感兴趣的:(解析微信小程序手机号异常 Exception:javax.crypto.BadPaddingException: Given final block not properly padded. S...)