-2
private static String bytesToString(byte[] encrypted) {
    //above method converts bytes to string
    String test = "";

    for (byte b : encrypted) {
        test += Byte.toString(b);
    }

    return test;
}

I have this method that converts bytes to String. How can I modify it so that it can convert the String to bytes?

halfer
  • 19,824
  • 17
  • 99
  • 186
eustace
  • 1
  • 1
  • Your String ( test ) has a method named .getBytes() to convert it to bytes. – Bart Jul 17 '18 at 09:32
  • Possible duplicate of [How to convert Java String into byte\[\]?](https://stackoverflow.com/questions/18571223/how-to-convert-java-string-into-byte) – dns_nx Jul 17 '18 at 09:40
  • 3
    Are you sure this is possible? Lets say you got "Alex" as string.. this gives array {65,108,101,120}. The method you got will give a string 6510801120. Forgetting java... how could you know hot to make this back to arrray? {65 10 80 11 20} and {65,108,101,120} are both valid .. Could you use a separater when concatenating the test string? – Alexandros Jul 17 '18 at 09:46
  • 1
    What should the bytes contain - an ASCII representation of each character? – halfer Jul 17 '18 at 18:03
  • Agreeing with @kumesana and erickson, you'd want a reversible scheme. Base64 and two-digit hexadecimal are typical; as are just letting a byte array be a byte array—that's what encryption/decryption algorithms operate on. – Tom Blodget Jul 17 '18 at 23:39

3 Answers3

3

That is impossible with the conversion you're doing.

Let's imagine the bytes you're "converting" are as so:

new byte[] {1, 0}

That's two bytes, and the resulting String is

"10"

Now let's imagine the bytes are as so:

new byte[] {10}

That's one byte, and the resulting String is

"10"

So, two different sequences of bytes can produce the same String "10". It is therefore impossible to decide whether String "10" should be converted back as {1, 0} or {10} or anything else.

kumesana
  • 2,495
  • 1
  • 9
  • 10
1

Your "modification" should be to use base-64 to encode and decode the byte array:

private static String bytesToString(byte[] encrypted) {
    return Base64.getUrlEncoder().encodeToString(encrypted);
}

private static byte[] stringToBytes(String encrypted) {
    return Base64.getUrlDecoder().decode(encrypted);
}

This will allow you to unambiguously encode any byte array, store and transmit it as text using only 7-bit, US-ASCII characters, then recover the original data.

erickson
  • 265,237
  • 58
  • 395
  • 493
-2

You can directly use String constructor.

String str = new String(bytes, StandardCharsets.UTF_8);

look at the documentation string constructor with bytecode

Ravat Tailor
  • 1,193
  • 3
  • 20
  • 44