I've following code to decrypt the files in Java which are encrypted via PHP mcrypt
function.
private String iv = "MYKEYHERE";//Dummy iv (CHANGE IT!)
private String SecretKey = "MYKEYHERE";//Dummy secretKey (CHANGE IT!)
private byte[] decrypt(String code)
{
byte[] decrypted = null;
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
SecretKeySpec keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
if(code == null || code.length() == 0)
throw new Exception("Empty string");
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
decrypted = cipher.doFinal(hexToBytes(code));
} catch (Exception e) {
e.printStackTrace();
}
return decrypted;
}
private static byte[] hexToBytes(String str) {
if (str==null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i<len; i++) {
try {
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return buffer;
}
}
and I'm reading and writing the files from SDCARD as
String encyptedData = readFileFromSDCard(params[0]);
byte[] decryptedByteArray = decrypt(encyptedData);
File rootFile = new File(Constants.folioTempLocation+params[1]);
rootFile.mkdirs();
File outFile = new File(rootFile, new File(params[0]).getName());
FileOutputStream out = new FileOutputStream(outFile);
//IOUtils.write(decryptedByteArray, out);
out.write(decryptedByteArray);
out.flush();
out.close();
There is no problem with decryption and writing files back to SD_CARD. But I'm getting unknown characters at the end of each file which is restricting the whole decrypted file to work properly.
I'm attaching screenshot of unknown characters concatenated to end of string. I'm also attaching an encrypted_html_file for anyone want to test the code using this file.
Screenshot