在Java中生成具有特定位大小的随机字符串 [英] Generate a random string with a specific bit size in java

查看:59
本文介绍了在Java中生成具有特定位大小的随机字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该怎么做?似乎找不到办法.Securerandom似乎不允许我在任何地方指定位大小

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

推荐答案

如果您的位数可以除以8,也就是说,您需要完整的字节数,则可以使用

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)

如果您不喜欢这些奇怪的字符,请将字节数组编码为base64:

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

例如,使用 Apache Commons Codec 并执行:

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

这篇关于在Java中生成具有特定位大小的随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆