Require similler java code for php encryption script -
i have php encryption function. need java counter part same. due limited knowledge in php unable understand. 1 knows both language, kindly help.
php code:
function encrypt($decrypted, $keyvalue) { // build 256-bit $key sha256 hash of $keyvalue. $key = hash('sha256', $keyvalue, true); // build $iv , $iv_base64. use block size of 128 bits (aes compliant) , cbc mode. (note: ecb mode inadequate iv not used.) srand(); $iv = mcrypt_create_iv(mcrypt_get_iv_size(mcrypt_rijndael_128, mcrypt_mode_cbc), mcrypt_rand); if (strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22) return false; // encrypt $decrypted , md5 of $decrypted using $key. md5 fine use here because it's verify successful decryption. $encrypted = base64_encode(mcrypt_encrypt(mcrypt_rijndael_128, $key, $decrypted . md5($decrypted), mcrypt_mode_cbc, $iv)); // we're done! return $iv_base64 . $encrypted; }
thanks in advance aniruddha
this should it.
public static byte[] encrypt(byte[] decrypted, byte[] keyvalue) throws nosuchalgorithmexception, nosuchpaddingexception, invalidkeyexception, invalidalgorithmparameterexception, illegalblocksizeexception, badpaddingexception{ messagedigest sha256 = messagedigest.getinstance("sha-256"); byte[] key = sha256.digest(keyvalue); messagedigest md5 = messagedigest.getinstance("md5"); byte[] checksum = md5.digest(decrypted); //the length of value encrypt must multiple of 16. byte[] decryptedandchecksum = new byte[(decrypted.length + md5.getdigestlength() + 15) / 16 * 16]; system.arraycopy(decrypted, 0, decryptedandchecksum, 0, decrypted.length); system.arraycopy(checksum, 0, decryptedandchecksum, decrypted.length, checksum.length); //the remaining bytes of decryptedandchecksum stay 0 (default byte value) because php pads 0's. securerandom rnd = new securerandom(); byte[] iv = new byte[16]; rnd.nextbytes(iv); ivparameterspec ivspec = new ivparameterspec(iv); cipher cipher = cipher.getinstance("aes/cbc/nopadding"); cipher.init(cipher.encrypt_mode, new secretkeyspec(key, "aes"), ivspec); byte[] encrypted = base64.encodebase64(cipher.dofinal(decryptedandchecksum)); byte[] ivbase64 = base64.encodebase64string(iv).substring(0, 22).getbytes(); byte[] output = new byte[encrypted.length + ivbase64.length]; system.arraycopy(ivbase64, 0, output, 0, ivbase64.length); system.arraycopy(encrypted, 0, output, ivbase64.length, encrypted.length); return output; }
the equivalent of mcrypt_rijndael_128 , mcrypt_mode_cbc in java aes/cbc/nopadding. need utility base64 encoding, above code uses base64
apache codec library.
also, because encryption key 256 bits, you'll need java cryptography extension (jce) unlimited strength jurisdiction policy files. these can downloaded oracle's website.
finally, heed ntoskrnl's warning. encryption better, don't copy-paste php manual.
Comments
Post a Comment