aes - Decrypt file in java failing on hash verification -
i using sample code project - c# implementation of encryption, in java
on decryption, file gets decrypted on verifying current hash old hash, last few bytes of old hash zeros , verification fails.
my java implementation of decrypt this:
private void mdecrypt_file(fileinputstream fin, string outfile) throws exception { fileoutputstream fout = new fileoutputstream(outfile); byte[] iv = new byte[16]; byte[] salt = new byte[16]; byte[] len = new byte[8]; byte[] fc_tagbuffer = new byte[8]; cipher cipher = cipher.getinstance(cipher_instance); datainputstream dis = new datainputstream(fin); dis.read(iv, 0, 16); dis.read(salt, 0, 16); rfc2898derivebytes rfc = new rfc2898derivebytes(default_password, salt, f_iterations); secretkey key = new secretkeyspec(rfc.getbytes(32), "aes"); //decryption code cipher.init(cipher.decrypt_mode, key, new ivparameterspec(iv)); cipherinputstream cin = new cipherinputstream(dis, cipher); cin.read(len, 0, 8); long lsize = getlong(len, 0); cin.read(fc_tagbuffer, 0, 8); byte[] tempfc_tagbuffer = changebytearray(fc_tagbuffer, 0);//new byte[8]; biginteger ulong = new biginteger(1, tempfc_tagbuffer); if (!ulong.equals(fc_tag)) { exception ex = new exception("tags not equal"); throw ex; } byte[] bytes = new byte[buffer_size]; //determine number of reads process on file long numreads = lsize / buffer_size; // determine left of file, after numreads long slack = (long) lsize % buffer_size; int read = -1; int value = 0; int outvalue = 0; messagedigest md = messagedigest.getinstance("sha-256"); md.reset(); // read buffer_sized chunks (int = 0; < numreads; ++i) { read = cin.read(bytes, 0, bytes.length); fout.write(bytes, 0, read); md.update(bytes, 0, read); value += read; outvalue += read; } // read slack if (slack > 0) { read = cin.read(bytes, 0, (int) slack); fout.write(bytes, 0, read); md.update(bytes, 0, read); value += read; outvalue += read; } fout.flush(); fout.close(); byte[] curhash = md.digest(); byte[] oldhash = new byte[md.getdigestlength()]; read = cin.read(oldhash, 0, oldhash.length); if (oldhash.length != read || (!checkbytearrays(oldhash, curhash))) { exception ex = new exception("file corrupted!"); throw ex; } if (outvalue != lsize) { exception ex = new exception("file sizes don't match!"); throw ex; } }
this decrypt method works on android not work in simple java project. file being encrypted java/android or .net.
thanks.