I try to decrypt in java a file, which was encrypted via openssl:
openssl enc -aes-256-ctr -in raw.zip -out encrypted.zip.enc -pass stdin
My implementation looks currently terrible, because it is just a scratch.
public static void main(String[] args)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
FileInputStream fis = new FileInputStream(new File("/tmp/encrypted.zip.enc"));
/* Derive the key, given password and salt. */
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] salt = new byte[8];
fis.read(salt, 0, 8);// Salted__
fis.read(salt, 0, 8);// real Salt
KeySpec spec = new PBEKeySpec("myPassphrase".toCharArray(), salt, 65536, 256);
SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
// build the initialization vector. This example is all zeros, but it
// could be any value or generated using a random number generator.
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secret, ivspec);
CipherInputStream inputStream = new CipherInputStream(fis, cipher);
FileOutputStream fos = new FileOutputStream(new File("/tmp/decrypted.zip"));
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
}
The file is not the same like before. the hashes differs. I guess, that there is a problem with the secret key. Is it right? Should I use another instances?