How to decrypt AES encrypted file with '-nosalt' param

大城市里の小女人 提交于 2019-12-03 00:50:45

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));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!