I want to be able to convert an ArrayList<String> that stores the contents of a file read from a BufferedReader, then convert the contents into a byte[] to allow it to be encrypted using Java's Cipher class.
I have tried using .getBytes() but it's not working since I think I need to convert the ArrayList first, and I'm having trouble on figuring out how to do that.
Code:
// 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));
}
Many thanks, in advance!
Either concatenate strings, or create a 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();
Why would you want to read it as string and the convert it to byte array? Since Java 7 you can do:
byte[] input= Files.readAllBytes(new File(userFile.toPath());
then pass that content to the Cipher.
byte[] output = cipher.doFinal(input);
Also you might consider using streams (InputStream and CipherOutputStream) instead of loading the whole file into the memory in case you need handle big files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With