簡體   English   中英

在AES / CBC / PKCS5Padding中獲取“ BadPaddingException:填充塊損壞”

[英]Getting 'BadPaddingException: pad block corrupted' in AES/CBC/PKCS5Padding

我的常數

 public static final String AES_ALGORITHM_MODE_PADDING = "AES/CBC/PKCS5Padding";
 public static final String AES = "AES";
 public static final String PROVIDER = "BC";

加密

   Cipher aesCipher = Cipher.getInstance(AES_ALGORITHM_MODE_PADDING, PROVIDER);
   SecretKeySpec aeskeySpec = new SecretKeySpec(rawAesKey, AES);
   aesCipher.init(Cipher.ENCRYPT_MODE, aeskeySpec);
   byte[] encryptedData = aesCipher.doFinal(data);
   this.iv = Base64.encodeBase64(aesCipher.getIV()); //get hold of the random IV

   return encryptedData;

在另一堂課中,我做解密

      IvParameterSpec ivspec = new IvParameterSpec(this.iv); //this is already been converted from base64 to raw form.

Cipher aesCipher = Cipher.getInstance(AES_ALGORITHM_MODE_PADDING, PROVIDER);
SecretKeySpec aeskeySpec = new SecretKeySpec(rawAesKey, AES);
aesCipher.init(Cipher.DECRYPT_MODE, aeskeySpec, ivspec);

return aesCipher.doFinal(rawEncryptedLicenseData);

現在,當我運行此程序時,解密時在doFinal上會收到BadPaddingException,我在做什么錯? 如果我刪除了CBC / PKCS5Padding和IV內容,而僅使用AES,它就可以工作!

您可以嘗試不帶填充的點擊率模式:

Cipher cipherAlg = Cipher.getInstance("AES/CTR/NoPadding", PROVIDER);
byte[] ivBytes = new byte[cipherAlg.getBlockSize()];
(new SecureRandom()).nextBytes(ivBytes);
cipherAlg.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(ivBytes));
byte[] cipher = cipherAlg.doFinal(plainText);
byte[] cipherText = new byte[ivBytes.length + cipher.length];
System.arraycopy(ivBytes, 0, cipherText, 0, ivBytes.length);
System.arraycopy(cipher, 0, cipherText, ivBytes.length, cipher.length);
return cipherText;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM