2010-07-05 54 views
1

我的常量 'BadPaddingException墊塊損壞'獲得:在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); 

現在,當我運行這個我得到一個BadPaddingException在doFinal解密時,我做錯了什麼?如果我刪除CBC/PKCS5Padding和IV的東西,只使用AES,它的工作原理!

+1

我看不出什麼毛病你是顯示的代碼。我懷疑你沒有正確地在課堂上移動IV。如果您可以在自包含的示例中重現問題(首先進行加密然後解密的一種方法),請嘗試嘗試。 – 2010-07-05 08:21:55

+0

你說得對。我註釋了我的RAW AES密鑰的保存,所以eclipse使用了之前的JUnit測試中的舊密鑰。 – jax 2010-07-05 09:13:44

回答

0

你可以嘗試CTR模式沒有填充:

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;