3

I am trying to convert the generate salt value which is in the byte[] format to String. But each time it converts in to special characters.

I used following way for converting byte[] to String :

byte[] salt = new byte[] { 50, 111, 8, 53, 86, 35, -19, -47 };
String saltString = new String(salt,"UTF-8");
System.out.println(saltString);

But output comes like ??@?

Naresh J
  • 2,087
  • 5
  • 26
  • 39
  • 1
    The salt is usually binary data. What makes you so sure it should encode a string? – Marko Topolnik May 31 '13 at 09:23
  • Are you looking for this : `StringBuilder sb = new StringBuilder(); for(byte b:salt){ char ch = (char)b; sb.append(ch); }` – AllTooSir May 31 '13 at 09:25
  • 1
    Salts are arbitrary binary data, and have no meaningful string representation. However, if you for example base64 encode them first then they will be entirely printable and represent the same thing. – Patashu May 31 '13 at 09:33

2 Answers2

4

you can convert using base64 encoding. to do this you can use javax.xml.bind.DatatypeConverter.printBase64Binary method

For example:

    byte[] salt = new byte[] { 50, 111, 8, 53, 86, 35, -19, -47 };
    System.out.println(DatatypeConverter.printBase64Binary(salt));

I would also like to add this answer

The "proper conversion" between byte[] and String is to explicitly state the encoding you want to use. If you start with a byte[] and it does not in fact contain text data, there is no "proper conversion". Strings are for text, byte[] is for binary data, and the only really sensible thing to do is to avoid converting between them unless you absolutely have to.

Community
  • 1
  • 1
stinepike
  • 54,068
  • 14
  • 92
  • 112
1

You can first convert it to base64 and the get string out of it.

byte[] salt = new byte[] { 50, 111, 8, 53, 86, 35, -19, -47 };
String encoded = new BASE64Encoder().encode(salt); 
System.out.print(encoded);