gpt4 book ai didi

java - 解密时文件被截断

转载 作者:行者123 更新时间:2023-12-02 08:20:38 24 4
gpt4 key购买 nike

我编写了以下代码来使用 java 加密库加密和解密文件。

import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

class Blowfish {
public static void main(String[] args) throws Exception {
String s;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Cipher encrypt = Cipher.getInstance("DES");
Cipher decrypt = Cipher.getInstance("DES");
System.out.print("Enter the key: ");
s = br.readLine();
/*
* Names of algorithms used "Blowfish" "DES" 64 bit key ie. 8 bytes
* "AES" key size has to be 16 bytes ie. 128 bits
*/

byte key[] = new byte[8];
for (int i = 0; i < s.length() && i < 8; i++)
key[i] = (byte) s.charAt(i);

encrypt.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "DES"));
FileInputStream fin = new FileInputStream("test.txt");
FileOutputStream out = new FileOutputStream("encrypted.p4e");
CipherOutputStream cout = new CipherOutputStream(out, encrypt);

int input = 0;
while ((input = fin.read()) != -1) {
cout.write(input);
}

out.close();
cout.close();
System.out.println("Starting the decryption");
System.out.print("Enter the key: ");
s = br.readLine();

byte key2[] = new byte[8];
for (int i = 0; i < s.length() && i < 8; i++)
key2[i] = (byte) s.charAt(i);

decrypt.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key2, "DES"));
fin = new FileInputStream("encrypted.p4e");
out = new FileOutputStream("test2.txt");
CipherInputStream in = new CipherInputStream(fin, decrypt);
input = 0;
while ((input = in.read()) != -1) {
out.write(input);
}
out.close();
in.close();
}
}

但是,当我尝试在示例 .txt 文件上测试它时,加密和解密运行时没有错误。然而,解密后的文件与原始文件并不完全相同...某些结尾部分被截断

测试文件

test file for encryption.. checking the correctness

使用 -> pralhad 加密

使用 key 解密后 -> pralhad

test file for encryption.. checking the

请提出一些解决方案。

最佳答案

您需要删除 crypted.p4e 的第一个 FileOutputStream 上的 out.close()。该流由 CipherOutputStream 包装,并且 cout.close() 将处理关闭底层流。通过提前关闭底层流,您将丢失 CipherOutputStream 为当前密码 block 缓冲的内容。

FileInputStream fin = new FileInputStream("test.txt");
FileOutputStream out = new FileOutputStream("encrypted.p4e");
CipherOutputStream cout = new CipherOutputStream(out, encrypt);
int input = 0;
while ((input = fin.read()) != -1) {
cout.write(input);
}
out.close(); // remove this line and it works
cout.close();

关于java - 解密时文件被截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5531542/

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