gpt4 book ai didi

java - 使用 FileReader 加密文件

转载 作者:行者123 更新时间:2023-12-01 17:55:43 26 4
gpt4 key购买 nike

在我的java程序中,我想读取一个.txt文件并随后对其进行编码。我知道如何读取文件并尝试学习如何对数组进行编码。我遇到的问题是我不知道如何组合它,它不像我尝试的那样工作。

这是我可以在文本文件中读取的部分:

public class ReadFile {

public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);

String zeile = "";

do
{
zeile = br.readLine();
System.out.println(zeile);
}
while (zeile != null);

br.close();
}
}

在这部分我可以加密和解密字节:

public class Crypt {

public static void main(String[] args) {

try{
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();

Cipher desalgCipher;
desalgCipher = Cipher.getInstance("DES");


byte[] text = "test".getBytes("UTF8");


desalgCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] textEncrypted = desalgCipher.doFinal(text);

String s = new String(textEncrypted);
System.out.println(s);

desalgCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] textDecrypted = desalgCipher.doFinal(textEncrypted);

s = new String(textDecrypted);
System.out.println(s);
}

catch(Exception e)
{
System.out.println("Error");
}
}

}

我想读取文本文件并将其放入字符串中进行编码,但我认为它太复杂了。是否有其他方法来连接它们,或者是否需要其他编码方法?

最佳答案

我强烈建议您使用Stream(请参阅https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.htmlhttps://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html),而不是直接使用FileReader

加密发生在比您尝试执行的更低的级别(字节)。Java 密码提供了方便的 CipherInputStream (和 CipherOutputStream)来动态加密字节流。与尝试将整个文件转储到单个 byte[] 中相比,它更便宜且更具可扩展性(更重要的是,因为您正在解码和重新编码文件内容)。

如果您想要使用示例,请查看以下代码片段:

public static void encrypt(Path inputFile, OutputStream output) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
// init cipher
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
Cipher desalgCipher;
desalgCipher = Cipher.getInstance("DES");
desalgCipher.init(Cipher.ENCRYPT_MODE, myDesKey);


try(InputStream is = Files.newInputStream(inputFile); // get an IS on your file
CipherInputStream cipherIS = new CipherInputStream(is, desalgCipher)){ // wraps input Stream with cipher
copyStreams(cipherIS, output); // copyStream is let to the implementer's choice.
}
}

我会让你弄清楚如何解密。

编辑:

无需担心编码问题而通信加密字节的常见方法是使用 Base 64 对原始字节进行编码。

您可以使用Base64.getEncoder().wrap(os) 包装outputStream

关于java - 使用 FileReader 加密文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45054924/

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