gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:12:14 28 4
gpt4 key购买 nike

我是加密新手。这个问题是我上一个问题的子问题。我有一个用 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 requires PBE parameters to be set.

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

最佳答案

使用empty salt 而不是null 并相应地设置offset

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

关于java - 如何使用 '-nosalt' 参数解密 AES 加密文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21696815/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com