Получение «BadPaddingException: блок панели поврежден» в AES / CBC / PKCS5Padding - PullRequest
1 голос
/ 05 июля 2010

Мои константы

 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 Ответ

0 голосов
/ 05 июля 2010

Вы можете попробовать режим 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;
...