Friday, 15 March 2013

Java encrypt/decript data from PHP to Java, IllegalBlockSizeException -



Java encrypt/decript data from PHP to Java, IllegalBlockSizeException -

i'm trying read base64 encoded , aes 128-bit encrypted string php, 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); homecoming base64_encode($enc); }

and returned value is:

mcbey73gq5fawxiunvkpquupiperlt9ntymrzjbpfti=

now want read in java:

static public string decrypt(string data) throws exception { info = 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") ); homecoming new string( bval ); }

and i'm getting exception:

javax.crypto.illegalblocksizeexception: info not block size aligned

this might caused padding?

edit

your error caused conversion of plaintext , string. it's not necessary anyway - utilize byte arrays:

byte[] info = base64 .decodebase64("mcbey73gq5fawxiunvkpquupiperlt9ntymrzjbpfti="); 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); system.out.println(new string(bval)); // prints f awesome test !

i recommend utilize padding in encryption, otherwise cannot cope arbitrarily-sized input.

java php aes encryption

No comments:

Post a Comment