如何使用'-naltalt'参数解密AES加密文件

时间:2014-02-11 08:38:24

标签: java android encryption aes password-encryption

我是加密新手。这个问题是我以前的问题。我有一个用OpenSSL util加密的文件:

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

我正在使用此代码对其进行解密:

        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);

它有效。但这是一个测试用例。真实情况是我用这些参数加密了文件:

  

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

注意'-nosalt'参数出现了。问题是PBEKeySpec要求不为空而不是空saltiterationsCount参数。它也有没有这些参数的构造函数但如果我使用它然后我得到一个错误:

  

02-11 11:25:06.108:W / System.err(2155):java.security.InvalidKeyException:PBE需要设置PBE参数。

问题是如何解密这些文件?如何正确处理'-naltalt'参数?

1 个答案:

答案 0 :(得分:2)

使用盐代替 null 并相应地设置偏移

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));
}