douda5706 2013-02-17 11:31
浏览 224

Java加密/解密从PHP到Java的数据,IllegalBlockSizeException

I'm trying to read a base64 encoded and AES 128-bit encrypted string from PHP, but I'm getting IllegalBlockSizeException.

PHP encrypt:

encrypt("My f awesome test !");

function encrypt($string){
    $td = mcrypt_module_open('rijndael-128', '', 'cbc', "1cc251f602cf49f2");

    mcrypt_generic_init($td, "f931c96c4a4e7e47", "1cc251f602cf49f2");
    $enc = mcrypt_generic($td, $string);

    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    return base64_encode($enc);
}

And the returned value is:

McBeY73GQ5fawxIunVKpqUupipeRlt9ntyMRzjbPfTI=

Now I want to read it in Java:

static public String decrypt(String data) throws Exception {
   data = new String( Base64.decode(data, Base64.NO_WRAP) );

   byte[] keyByte = "f931c96c4a4e7e47".getBytes("UTF-8");
   byte[] ivByte = "1cc251f602cf49f2".getBytes("UTF-8");

   Key key = new SecretKeySpec(keyByte, "AES");
   IvParameterSpec iv = new IvParameterSpec(ivByte);
   Cipher c = Cipher.getInstance("AES/CBC/NoPadding");
   c.init(Cipher.DECRYPT_MODE, key, iv);
   byte[] bval = c.doFinal( data.getBytes("UTF-8") );

   return new String( bval );
}

And I'm getting an Exception:

javax.crypto.IllegalBlockSizeException: data not block size aligned

This might be caused by padding?

EDIT

enter image description here

  • 写回答

3条回答 默认 最新

  • dssjxvbv918586 2013-02-17 11:43
    关注

    the IllegalBlockSizeException thrown on call to doFinal() if: "cipher is a block cipher, no padding has been requested (only in encryption mode), and the total input length of the data processed by this cipher is not a multiple of block size; or if this encryption algorithm is unable to process the input data provided." -http://docs.oracle.com/javase/6/docs/api/javax/crypto/Cipher.html#doFinal%28%29. So its either bad input data or block size.

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!