解密时文件被截断

时间:2011-04-03 18:23:23

标签: java encryption

我已经编写了以下代码来使用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文件上测试它时,加密和解密运行没有错误。然而,解密文件与原始文件不完全相同......某些结尾部分是截断

测试文件

  

用于加密的测试文件..检查   正确性

使用 - &gt;加密pralhad

使用密钥解密后 - &gt; pralhad

  

用于加密的测试文件..检查   在

请提出一些解决方案。

3 个答案:

答案 0 :(得分:1)

您需要删除out.close()的第一个FileOutputStream上的encrypted.p4e。该流由CipherOutputStream包裹,cout.close()将处理关闭基础流。通过提前关闭该基础流,您将丢失为当前密码块缓冲的CipherOutputStream

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

答案 1 :(得分:1)

key[i]=(byte)s.charAt(i);

由于这个事实,Java的字符大小是2个字节,我认为将char转换为字节存在问题。一半的信息将被截断。如果使用除前128个字符之外的其他字符,则会很苛刻。

答案 2 :(得分:0)

在关闭cout来电flush()之前尝试:

cout.flush()