Generate a random string with a specific bit size in java

前端 未结 4 1575
醉话见心
醉话见心 2020-12-20 14:34

How do i do that? Can\'t seems to find a way. Securerandom doesn\'t seems to allow me to specify bit size anywhere

4条回答
  •  不思量自难忘°
    2020-12-20 15:07

    Similar to the other answer with a minor detail

    Random random = ThreadLocalRandom.current();
    byte[] randomBytes = new byte[32];
    random.nextBytes(randomBytes);
    String encoded = Base64.getUrlEncoder().encodeToString(randomBytes)
    

    Instead of simply using Base64 encoding, which can leave you with a '+' in the out, make sure it doesn't contain any characters which need to be further URL encoded.

提交回复
热议问题