29

I'm generating a random string using:

private String generateSafeToken() {
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[512];
    random.nextBytes(bytes);
    return bytes.toString();
}

This gives a string of length 11 such as [B@70ffc557. How can I make this above method return a string of a specified length. For example 20 characters?

kovac
  • 4,945
  • 9
  • 47
  • 90
  • 2
    You can't convert bytes to a string like that. toString for an array is not a string representation of the contents of the array. `SecureRandom` is giving you back 512 bytes as expected. – pvg Sep 17 '17 at 05:38
  • @pvg I'm trying to generate a token and save it in Postgres db. I tried `new String(bytes)` but I get a `invalid byte sequence for encoding "UTF8"` error. Can you advise how to go about this, please? – kovac Sep 17 '17 at 05:47
  • your question is a duplicate, check out the dupe or literally google 'generate a string token with securerandom' and pick one of the 881123 solutions. – pvg Sep 17 '17 at 05:48
  • 1
    unfortunately stackoverflow has become a place for some people to prove their "knowledge" by gathering repotation and one good way of that is going around and acting on other's question totally out of the scope and just in editorial context. don't let them discourage you finding your answer! – mohamnag Apr 07 '18 at 19:19
  • Is the question how to generate a random string of a given length with secure random? Or how to encode any byte array as text? Both questions are duplicates. – erickson May 17 '18 at 16:23

2 Answers2

50

I don't understand why this is marked duplicate when clearly the "duplicate" question referred here doesn't ask the same question - though an answer down below contains this information. In any case, the answer I was looking for is below, incase if it helps anyone else.

private String generateSafeToken() {
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[20];
    random.nextBytes(bytes);
    Encoder encoder = Base64.getUrlEncoder().withoutPadding();
    String token = encoder.encodeToString(bytes);
    return token;
}
kovac
  • 4,945
  • 9
  • 47
  • 90
0

bytes.toString(); is wrong, try using Arrays.toString(bytes) - or new String(bytes) if you want to convert it to a String.

Dorian Gray
  • 2,913
  • 1
  • 9
  • 25