How to decrypt AES encrypted file with '-nosal

2020-05-22 00:39发布

问题:

I'm new to encryption. This question is subquestion of my previous one. I have a file encrypted with OpenSSL util:

openssl aes-256-cbc -in fileIn -out fileOUT -p -k KEY

I'm using this code to decrypt it:

        byte[] encrypted = IOUtils.toByteArray(inputStream);
        Security.addProvider(new BouncyCastleProvider());

        String password = "abc";

        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");

        // Openssl puts SALTED__ then the 8 byte salt at the start of the
        // file. We simply copy it out.
        byte[] salt = new byte[8];
        System.arraycopy(encrypted, 8, salt, 0, 8);
        SecretKeyFactory fact = SecretKeyFactory.getInstance(
                "PBEWITHMD5AND256BITAES-CBC-OPENSSL", "BC");
        c.init(Cipher.DECRYPT_MODE, fact.generateSecret(new PBEKeySpec(
                password.toCharArray(), salt, 100)));

        // Decrypt the rest of the byte array (after stripping off the salt)
        byte[] data = c.doFinal(encrypted, 16, encrypted.length - 16);

And it works. But this is a test case. The real situation is that I have file encrypted with these params:

openssl aes-256-cbc -nosalt -in fileIn -out fileOUT -p -k KEY

Notice that '-nosalt' param appeared. The issue is that PBEKeySpec requires not null and not empty salt and iterationsCount params. It also have constructor without these params but if I use it then I get an error:

02-11 11:25:06.108: W/System.err(2155): java.security.InvalidKeyException: PBE requires PBE parameters to be set.

The question is how to decrypt these files? How to handle '-nosalt' param correctly?

回答1:

Use empty salt instead of null and set offset accordingly

Security.addProvider(new BouncyCastleProvider());

final char[] password = "pass".toCharArray();
final int saltLength = 8;
final String saltedPrefix = "Salted__";

String[] files = { "file0.txt.enc", "file0.txt.enc.nosalt" };
for (String file : files) {
    byte[] encrypted = Files.readAllBytes(Paths.get("testData", "openssl", file));

    byte[] salt = new byte[0];
    int offset = 0;
    if (new String(encrypted, 0, saltLength, "ASCII").equals(saltedPrefix)) {
        salt = new byte[saltLength];
        System.arraycopy(encrypted, saltedPrefix.length(), salt, 0, saltLength);
        offset = saltedPrefix.length() + saltLength;
    }

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWITHMD5AND256BITAES-CBC-OPENSSL", "BC");
    PBEKeySpec keySpec = new PBEKeySpec(password);
    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 0);
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.DECRYPT_MODE, keyFactory.generateSecret(keySpec), paramSpec);

    byte[] data = cipher.doFinal(encrypted, offset, encrypted.length- offset);
    System.out.println(new String(data));
}