mun*_*ong 1 java string encryption byte arraylist
我希望能够转换ArrayList<String>存储从BufferedReader读取的文件内容的内容,然后将内容转换为byte [],以允许使用Java的Cipher类对其进行加密.
我尝试过使用.getBytes()但它没有工作,因为我认为我需要首先转换ArrayList,而我在弄清楚如何做到这一点时遇到了麻烦.
码:
// File variable
private static String file;
// From main()
file = args[2];
private static void sendData(SecretKey desedeKey, DataOutputStream dos) throws Exception {
ArrayList<String> fileString = new ArrayList<String>();
String line;
String userFile = file + ".txt";
BufferedReader in = new BufferedReader(new FileReader(userFile));
while ((line = in.readLine()) != null) {
fileString.add(line.getBytes()); //error here
}
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, desedeKey);
byte[] output = cipher.doFinal(fileString.getBytes("UTF-8")); //error here
dos.writeInt(output.length);
dos.write(output);
System.out.println("Encrypted Data: " + Arrays.toString(output));
}
Run Code Online (Sandbox Code Playgroud)
提前谢谢了!
连接字符串,或创建一个StringBuffer.
StringBuffer buffer = new StringBuffer();
String line;
String userFile = file + ".txt";
BufferedReader in = new BufferedReader(new FileReader(userFile));
while ((line = in.readLine()) != null) {
buffer.append(line); //error here
}
byte[] bytes = buffer.toString().getBytes();
Run Code Online (Sandbox Code Playgroud)
为什么要将其作为字符串读取并将其转换为字节数组?从Java 7开始,您可以:
byte[] input= Files.readAllBytes(new File(userFile.toPath());
Run Code Online (Sandbox Code Playgroud)
然后将该内容传递给密码.
byte[] output = cipher.doFinal(input);
Run Code Online (Sandbox Code Playgroud)
您也可以考虑使用流(InputStream和CipherOutputStream),而不是将整个文件加载到内存中,以防您需要处理大文件.
| 归档时间: |
|
| 查看次数: |
457 次 |
| 最近记录: |