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.

    评论

报告相同问题?

悬赏问题

  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)