Stream cipher using java

1.6k views Asked by At

I'm trying to create a Stream cipher using Java in which I take plain text from the file encrypt it (Simple XOR with a random key with seed value) and the store it in a different file and then to decrypt, again take cipher text from the file and decrypt it (same XOR operation with key as encryption) and storing in a file.

But I'm facing problem when I tried to encrypt large string. Half of the string is being decrypted correctly but the other half remains in unreadable format.

                FileReader fileReader = new FileReader(file);

                // Always wrap FileReader in BufferedReader.
                BufferedReader bufferedReader = 
                    new BufferedReader(fileReader);

                FileWriter fileWriter =
                        new FileWriter(file2);

                    // Always wrap FileWriter in BufferedWriter.
                    BufferedWriter bufferedWriter =
                        new BufferedWriter(fileWriter);


                while((line = bufferedReader.readLine()) != null) {
                    sb = new StringBuffer (line);

                    int lenStr = line.length();
                    int lenKey = String.valueOf(random).length();

                    // For each character in our string, encrypt it...
                    for ( int i = 0, j = 0; i < lenStr; i++, j++ ) 
                    {
                       if ( j >= lenKey ) j = 0;  // Wrap 'round to beginning of key string.

                       //
                       // XOR the chars together. Must cast back to char to avoid compile error. 
                       //
                       String key = random + "";
                       bufferedWriter.write((char)(line.charAt(i) ^ key.charAt(j)));

                    }
                }   

                // Always close files.
                bufferedReader.close();  
                bufferedWriter.close();
1

There are 1 answers

3
Maarten Bodewes On

You are mixing binary and characters and strings without enough care. The XOR'ing of characters may well result in a character not representing a string. If two identical characters are XOR'ed together then the result will be a null character, usually interpreted as END of FILE.

Instead it is best to keep everything binary when XOR'ing. XOR is a binary operation, not an operation on characters. So you use byte arrays instead.