How to read /write XORed txt file UTF8 in java?

what i did so far :

I read a file1 with text, XORed the bytes with a key and wrote it back to another file2. My problem: I read for example 'H' from file1 , the byte value is 72;

72 XOR -32 = -88 Now i wrote -88 in to the file2. when i read file2 i should get -88 as first byte, but i get -3.

public byte[] readInput(String File) throws IOException {

    Path path = Paths.get(File);
    byte[] data = Files.readAllBytes(path);
    byte[]x=new byte[data.length ];

    FileInputStream fis = new FileInputStream(File);
    InputStreamReader isr = new InputStreamReader(fis);//utf8
    Reader in = new BufferedReader(isr);
    int ch;
    int s = 0;
    while ((ch = in.read()) > -1) {// read till EOF
        x[s] = (byte) (ch);
    }
    in.close();

    return x;


}




public void writeOutput(byte encrypted [],String file) {
    try {

        FileOutputStream fos = new FileOutputStream(file);
        Writer out = new OutputStreamWriter(fos,"UTF-8");//utf8

        String s = new String(encrypted, "UTF-8");

        out.write(s);
        out.close();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}



 public byte[]DNcryption(byte[]key,byte[] mssg){

    if(mssg.length==key.length)
    {
        byte[] encryptedBytes= new byte[key.length];

        for(int i=0;i<key.length;i++)
        {
            encryptedBytes[i]=Byte.valueOf((byte)(mssg[i]^key[i]));//XOR

        }
        return encryptedBytes;
    }
    else
    {
        return null;
    }

}   
Jon Skeet
people
quotationmark

You're not reading the file as bytes - you're reading it as characters. The encrypted data isn't valid UTF-8-encoded text, so you shouldn't try to read it as such.

Likewise, you shouldn't be writing arbitrary byte arrays as if they're UTF-8-encoded text.

Basically, your methods have signatures accepting or returning arbitrary binary data - don't use Writer or Reader classes at all. Just write the data straight to the stream. (And don't swallow the exception, either - do you really want to continue if you've failed to write important data?)

I would actually remove both your readInput and writeOutput methods entirely. Instead, use Files.readAllBytes and Files.write.

people

See more on this question at Stackoverflow