【发布时间】:2020-01-20 13:59:30
【问题描述】:
我尝试在 java 中解密一个通过 openssl 加密的文件:
openssl enc -aes-256-ctr -in raw.zip -out encrypted.zip.enc -pass stdin
我的实现目前看起来很糟糕,因为它只是一个划痕。
public static void main(String[] args)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
FileInputStream fis = new FileInputStream(new File("/tmp/encrypted.zip.enc"));
/* Derive the key, given password and salt. */
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] salt = new byte[8];
fis.read(salt, 0, 8);// Salted__
fis.read(salt, 0, 8);// real Salt
KeySpec spec = new PBEKeySpec("myPassphrase".toCharArray(), salt, 65536, 256);
SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
// build the initialization vector. This example is all zeros, but it
// could be any value or generated using a random number generator.
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secret, ivspec);
CipherInputStream inputStream = new CipherInputStream(fis, cipher);
FileOutputStream fos = new FileOutputStream(new File("/tmp/decrypted.zip"));
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
}
文件和以前不一样了。哈希值不同。我猜,密钥有问题。这样对吗?我应该使用其他实例吗?
【问题讨论】:
-
你从哪里复制你的实现?也许这个answer 可能会有所帮助。
-
@Boris:这通常是基于密码的,但与 openssl 不兼容(除非如 Zergatul 所说,openssl 1.1.1 带有 -pbkdf2)。而是看到stackoverflow.com/questions/14695766stackoverflow.com/questions/11783062stackoverflow.com/questions/31947256stackoverflow.com/questions/32508961stackoverflow.com/questions/29151211
标签: java algorithm encryption cryptography aes