0

I am using the JNCryptor library to encrypt a string before sending it to my server as an encrypted string. Here is my code:

    String teststring = "Hello World";
    JNCryptor cryptor = new AES256JNCryptor();
    byte[] plaintext = teststring.getBytes();
    String password = "test";

    try {
        byte[] ciphertext = cryptor.encryptData(plaintext, password.toCharArray());

        String a = new String(ciphertext);
        return a;


    } catch (CryptorException e) {
        // Something went wrong
        e.printStackTrace();

        return "0";
    }

However, when I send my string "a" to the server, it has a bunch of unrecognizable characters. I read an explanation regarding this:

String is not a suitable container for binary data and ciphertext is binary data. For any given character encoding not all bytes and byte sequences represents characters and when an un-representable byte or sequence is found it is converted to some error character. Obviously this error character cannot be converted back to a unique byte or byte sequence (it is a many->one mapping).

Is this advice correct? In that case, how do I convert the byte[] to a string correctly? So that I can readably store it on my server?

1
  • 1
    The advice is correct. Failure to heed it will lead to tears. Commented Jul 22, 2014 at 22:29

1 Answer 1

4

There is no standard way for converting from a byte array to a string. You have to encode the byte array. A common way to do this is base64 encoding. For an explanation of how base64 encoding works: http://en.wikipedia.org/wiki/Base64

Then once it gets to your server, base64 decode it back into your original byte array and store it, done!

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

1 Comment

On Android this is accessible in the android.util.Base64 class. I don't know iOS.

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.