0

我试图读取我的加密文件并将其解密的内容放入一个列表中,但是最后的一些行随机拆分或一半到一个新行。有什么想法为什么要这样做?(在解密方法中)。顺便说一句,如果有帮助,缓冲区是 1024。

public Crypto() {
    try {
        PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(keySpec);
        ecipher = Cipher.getInstance("PBEWithMD5AndDES");
        dcipher = Cipher.getInstance("PBEWithMD5AndDES");
        byte[] salt = new byte[8];
        PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
        ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        } catch (Exception e) {
    }
}

@SuppressWarnings("resource")
public static List<String> decrypt(String file) {
    List<String> list = new LinkedList<String>();
    try {
        InputStream in = new CipherInputStream(new FileInputStream(file), dcipher);
        int numRead = 0;
        while ((numRead = in.read(buffer)) >= 0) {
            list.add(new String(buffer, 0, numRead);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list;
}
4

1 回答 1

1

a 上的read方法Stream只是将多个Bytes 读入缓冲区。因此,您的代码以 1024 大小的块读取文件,并将读取的每个块保存到List.

有几种方法可以Stream逐行阅读,我会推荐BufferedReader

final List<String> list = new LinkedList<String>();
try {
    final BufferedReader reader = new BufferedReader(new InputStreamReader(new CipherInputStream(new FileInputStream(file), dcipher)));
    String line;
    while ((line = reader.readLine()) != null) {
        list.add(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

需要注意的一件事在很多场合都让我感到困惑,那就是它InputStreamReader会进行隐式转换Byte-String这需要编码。默认情况下,将使用平台编码,这意味着您的代码是平台相关的。您的原始代码new String(byte[])也是如此,默认情况下也使用平台编码。

我建议始终明确指定编码:

final BufferedReader reader = new BufferedReader(new InputStreamReader(new CipherInputStream(new FileInputStream(file), dcipher), "UTF-8"));

或者对于String构造函数

new String(bytes, "UTF-8")

String任何将 a 写入a 的代码也是如此File

try {
    try (final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new CipherOutputStream(new FileOutputStream(file), dcipher), "UTF-8"))) {
        writer.append(data);
    }
} catch (IOException ex) {
    e.printStackTrace();
}

这样,您可以避免在不同操作系统上运行应用程序时出现令人讨厌的意外,因为每个系列都使用不同的默认编码(UTF-8在 Linux、ISO-8859-1Windows 和MacRomanMac 上)。

另一个注意事项是您不要关闭您的Stream(或Reader现在) - 这是必要的,它可以finally在 java 6 中的 a 或使用 java 7 的新try-with-resources构造中完成。

try (final BufferedReader reader = new BufferedReader(new InputStreamReader(new CipherInputStream(new FileInputStream(file), dcipher), "UTF-8"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        list.add(line);
    }
}
于 2013-03-23T10:53:52.373 回答