How to generate a SecureRandom string of length n in Java? [duplicate]

自闭症网瘾萝莉.ら 提交于 2019-12-08 16:14:58

问题


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?


回答1:


I don't understand why this is marked duplicate when clearly the "duplicate" question referred here doesn't answer the question. 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;
}



回答2:


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



来源:https://stackoverflow.com/questions/46261055/how-to-generate-a-securerandom-string-of-length-n-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!