Im trying to implement file decryption by referring this code:
Encryption part i have done this way: https//stackoverflow.com/questions/64423926/encrypt-file-in-java-and-decrypt-in-openssl-with-key-aes
And the encrypted file im able to decrypt with openssl.
But the decrypt to file in java is causing error:
java.lang.IllegalArgumentException: Illegal base64 character 5f
at java.util.Base64$Decoder.decode0(Unknown Source)
at java.util.Base64$Decoder.decode(Unknown Source)
at java.util.Base64$Decoder.decode(Unknown Source)
at aes.AesEncryptTask.decryptNew(AesEncryptTask.java:107)
at aes.AesEncryptTask.main(AesEncryptTask.java:58)
Content in my encrypted file is:
Salted__¨‹–1ž#¡ð=—ÖÏùá•NEÄ
Note: Starting salted part is not base64encoded. following data is encoded.
Please suggest on correct implementation of file decryption.
static void decryptNew(String path,String password, String outPath) {
try{
FileInputStream fis = new FileInputStream(path);
FileOutputStream fos = new FileOutputStream(outPath);
final byte[] pass = password.getBytes(StandardCharsets.US_ASCII);
//final byte[] inBytes = Base64.getDecoder().decode(source);
String source = getFileContent(fis);
final Decoder decoder = Base64.getDecoder();
final byte[] inBytes = decoder.decode(source);
//final byte[] inBytes =source.getBytes();//DatatypeConverter.parseBase64Binary(source);
final byte[] shouldBeMagic = Arrays.copyOfRange(inBytes, 0, SALTED_MAGIC.length);
if (!Arrays.equals(shouldBeMagic, SALTED_MAGIC)) {
throw new IllegalArgumentException("Initial bytes from input do not match OpenSSL SALTED_MAGIC salt value.");
}
final byte[] salt = Arrays.copyOfRange(inBytes, SALTED_MAGIC.length, SALTED_MAGIC.length + 8);
final byte[] passAndSalt = array_concat(pass, salt);
byte[] hash = new byte[0];
byte[] keyAndIv = new byte[0];
for (int i = 0; i < 3 && keyAndIv.length < 48; i++) {
final byte[] hashData = array_concat(hash, passAndSalt);
MessageDigest md = null;
md = MessageDigest.getInstance("SHA-1");
hash = md.digest(hashData);
keyAndIv = array_concat(keyAndIv, hash);
}
final byte[] keyValue = Arrays.copyOfRange(keyAndIv, 0, 32);
final SecretKeySpec key = new SecretKeySpec(keyValue, "AES");
final byte[] iv = Arrays.copyOfRange(keyAndIv, 32, 48);
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
final byte[] clear = cipher.doFinal(inBytes, 16, inBytes.length - 16);
String contentDecoded = new String(clear, StandardCharsets.UTF_8);
fos.write(contentDecoded.getBytes());
fos.close();
//cipher.init(Cipher.DECRYPT_MODE, sks);
/*CipherInputStream cis = new CipherInputStream(fis, cipher);
int b;
byte[] d = new byte[8];
while((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();*/
System.out.println("Decrypt is completed");
}catch(Exception e){
e.printStackTrace();
}
}