Generate a random string with a specific bit size in java

前端 未结 4 1586
醉话见心
醉话见心 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:15

    If your bit-count can be divded by 8, in other words, you need a full byte-count, you can use

    Random random = ThreadLocalRandom.current();
    byte[] r = new byte[256]; //Means 2048 bit
    random.nextBytes(r);
    String s = new String(r)
    

    If you don't like the strange characters, encode the byte-array as base64:

    For example, use the Apache Commons Codec and do:

    Random random = ThreadLocalRandom.current();
    byte[] r = new byte[256]; //Means 2048 bit
    random.nextBytes(r);
    String s = Base64.encodeBase64String(r);
    

提交回复
热议问题