首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BlackBerry解密- BadPaddingException

BlackBerry解密- BadPaddingException
EN

Stack Overflow用户
提问于 2013-01-16 15:33:35
回答 2查看 419关注 0票数 1

我已经成功地在BlackBerry中加密了AES格式的数据。为了验证我的结果,我尝试使用以下方法在BlackBerry中实现解密:

代码语言:javascript
复制
 private static byte[] decrypt( byte[] keyData, byte[] ciphertext )throws CryptoException, IOException
{
   // First, create the AESKey again.
   AESKey key = new AESKey( keyData );

   // Now, create the decryptor engine.
   AESDecryptorEngine engine = new AESDecryptorEngine( key );
   // Since we cannot guarantee that the data will be of an equal block length
   // we want to use a padding engine (PKCS5 in this case).
   PKCS5UnformatterEngine uengine = new PKCS5UnformatterEngine( engine );

   // Create the BlockDecryptor to hide the decryption details away.
   ByteArrayInputStream input = new ByteArrayInputStream( ciphertext );
   BlockDecryptor decryptor = new BlockDecryptor( uengine, input );

   // Now, read in the data. Remember that the last 20 bytes represent
   // the SHA1 hash of the decrypted data.
   byte[] temp = new byte[ 100 ];
   DataBuffer buffer = new DataBuffer();

   for( ;; ) {
       int bytesRead = decryptor.read( temp );
       buffer.write( temp, 0, bytesRead );

       if( bytesRead < 100 ) {
           // We ran out of data.
           break;
       }
   }

   byte[] plaintextAndHash = buffer.getArray();
   int plaintextLength = plaintextAndHash.length - SHA1Digest.DIGEST_LENGTH;
   byte[] plaintext = new byte[ plaintextLength ];
   byte[] hash = new byte[ SHA1Digest.DIGEST_LENGTH ];

   System.arraycopy( plaintextAndHash, 0, plaintext, 0, plaintextLength );
   System.arraycopy( plaintextAndHash, plaintextLength, hash, 0,
       SHA1Digest.DIGEST_LENGTH );

   // Now, hash the plaintext and compare against the hash
   // that we found in the decrypted data.
   SHA1Digest digest = new SHA1Digest();
   digest.update( plaintext );
   byte[] hash2 = digest.getDigest();

   if( !Arrays.equals( hash, hash2 )) {
       throw new RuntimeException();
   }

   return plaintext;
}

我在下面的行抛出一个异常"BadPaddingException“

代码语言:javascript
复制
int bytesRead = decryptor.read( temp );

有谁能帮帮忙。

EN

回答 2

Stack Overflow用户

发布于 2013-01-16 16:57:42

您的加密数据应正确填充到块大小(16字节)。尝试在没有填充的情况下解密数据,并查看尾字节是否对应于PKCS#5填充(例如,如果需要5个字节的填充,则应附加0x05 0x05 0x05字节)。

票数 1
EN

Stack Overflow用户

发布于 2013-01-17 08:34:17

问题是,任何具有正确块大小的数据都将被解密。这样做的问题是,它很可能会解密成随机的垃圾。随机看垃圾通常与PKCS#7填充方案不兼容,因此出现了例外。

我之所以说是问题,是因为如果键数据无效,如果使用了错误的填充或块模式,或者仅仅是如果输入数据在处理过程中被篡改,则可能会抛出此异常。对此进行调试的最佳方法是100%确保算法匹配,并且二进制输入参数(包括API的默认参数)在两端都精确匹配。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14353346

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档