1

I am performing xor encryption in Java. It encrypts a byte array, converts it into a String, and then prints the String.

However, when I execute it, I get strange "boxes" in the output (Eclipse console).

The algorithm code:

for(int i = 0; i < messageArr.length; i++)
{
    encryptedMessage[i] = (byte) (messageArr[i]^codebookArr[i]);
}

String eMessage = new String(encryptedMessage);
return eMessage;

The main method:

String lMessage = e.xorEncrypt(message, codebook);
System.out.println("Encrypted message: " + lMessage);
String uMessage = e.xorEncrypt(lMessage, codebook);
System.out.println("Unencrypted message: " + uMessage);

When I run this code, it prints strange "boxes" for the encrypted string. However, when it decrypts the string, I receive the original output, showing that the encryption algorithm works.

Why do I receive the strange boxes for the encrypted output, but the correct string when I decrypt it?

7
  • Can you provide the data of message and codebook? Commented May 6, 2017 at 7:07
  • You get boxes because they are not readable ascii characters Commented May 6, 2017 at 7:07
  • 1
    You're trying to transform arbitrary, binary bytes to a String, using the platform default encoding. You can't expect to get back only valid, printable characters. Not all byte sequences are valid character sequences in all encodings, and not all characters are printable. Commented May 6, 2017 at 7:08
  • 1
    Why do you expect something printable when you print the encrypted stuff? Commented May 6, 2017 at 7:08
  • 1
    Sure. Use Base64 encoding to transform the arbitrary byte array into a sequence of printable characters. Commented May 6, 2017 at 7:30

1 Answer 1

1

You can use Base64 encoding after encryption (it is a best practice) so you don't get weird boxes and no special characters get lost in "travel".

A good reference:

Base64 Encoding in Java

You will get a string somewhat like this: b2xkIGNyb3cgbWVkaWNpbmUgc2hvdw==

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.