Generate a random string with a specific bit size in java

前端 未结 4 1573
醉话见心
醉话见心 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.

    0 讨论(0)
  • 2020-12-20 15:11

    The meaning of "random String" is not clear in Java.

    You can generate random bits and bytes, but converting these bytes to a string is normally not simply doable, as there is no build-in conversion which accepts all byte arrays and outputs all strings of a given length.

    If you only want random bytes, do what theomega proposed, and ommit the last line.

    If you want a random string of some set of characters, it depends on the set. Base64 is an example such set, using 64 different ASCII characters to represent 6 bit each (so 4 of these characters represent 24 bit, which would be 3 bytes.)

    0 讨论(0)
  • 2020-12-20 15:14

    If you're interested in a random unique 128 bit string, I'd recommend UUID.randomUUID()

    Alternatives would include ...

    • http://jug.safehaus.org/
    • http://johannburkard.de/software/uuid/
    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题