2021-05-27

SecureRandom与Random

API:

	1:Random 此类的实例用于生成伪随机数流。
	2:SecureRandom 此类提供强加密随机数生成器 (RNG)。

Random

Random用来创建伪随机数。所谓伪随机数,是指只要给定一个初始的种子,产生的随机数序列是完全一样的。
要生成一个随机数,可以使用nextInt()、nextLong()、nextFloat()、nextDouble():

Random r = new Random();
r.nextInt(); // 每次都不一样
r.nextInt(10); // 生成一个[0,10)之间的int
r.nextLong(); // 每次都不一样
r.nextFloat(); // 生成一个[0,1)之间的float
r.nextDouble(); // 生成一个[0,1)之间的double

SecureRandom

有伪随机数,就有真随机数。实际上真正的真随机数只能通过量子力学原理来获取,而我们想要的是一个不可预测的安全的随机数,SecureRandom就是用来创建安全的随机数,生成一个包含用户指定伪随机位数的整数(右对齐,带前导零)。此方法将重写 java.util.Random 方法,并将为继承自类的所有方法(例如,nextInt、nextLong 和 nextFloat)提供随机位源。
SecureRandom sr = new SecureRandom();
sr.nextInt(); // 每次都不一样
sr.nextInt(10); // 生成一个[0,10)之间的int
sr.nextLong(); // 每次都不一样
sr.nextFloat(); // 生成一个[0,1)之间的float

SecureRandom的安全性是通过操作系统提供的安全的随机种子来生成随机数。
在密码学中,安全的随机数非常重要。如果使用不安全的伪随机数,所有加密体系都将被攻破。因此,时刻牢记必须使用SecureRandom来产生安全的随机数。
需要使用安全随机数的时候,必须使用SecureRandom,绝不能使用Random!

实例

public void test (HttpServletRequest request, HttpServletResponse response)
//获取数据库最后保存的值
Command maxCommand = new Command(conditions);
Dto result = (Dto) maxCommand.execute();
//调用生成方法
String codeCode = createNext(result.Code());
//校验生成内容是否重复
codeCode = run(Dto.getCodeType(),codeCode,result.getCode());
}
@SuppressWarnings(“finally”)//重复校验方法,重复后重新生成
public String run(String codeType,String codecode, String maxCode) {
String key = “”;
try {
PrimaryKeyCommand command = new PrimaryKeyCommand(codeType, codecode);
//execute()获取数据库内容为空会空指针异常
if(null != command.execute()){
codecode = createNext(maxCode);
key = run(codeType,codecode,maxCode);
}
//捕捉空指针异常正常赋值
} catch (Exception e) {
key = codecode;
}finally{
return key;
}
}
//生成key方法,方法不仅值生成两位随机数,单位字母时顺序增加1位
public static String createNext(String string){
char [] tempChar = string.toCharArray();
//取最后1位
for(int i =tempChar.length-1;i>=0;i–){
if (tempChar[i]<‘Z’ ){
tempChar[i]=(char)(tempChar[i]+1);
break;
}else {
tempChar[i]=‘A’;
if((i-1 >= 0) && tempChar.length <= 1){
tempChar[i-1]=(char)(tempChar[i-1]+1);
if (tempChar[i-1]<=‘A’){
i=0;
}
break;
}else{
char[] str = new char[]{‘A’,‘B’,‘C’,‘D’,‘E’,‘F’,‘G’,‘H’,‘I’,‘G’,‘K’,‘L’,‘M’,‘N’,‘O’,‘P’,‘Q’,‘R’,‘S’,‘T’,‘U’,‘V’,‘W’,‘X’,‘Y’,‘Z’};
SecureRandom random = new SecureRandom();
if(tempChar.length <= 1){
tempChar = Arrays.copyOf(tempChar,tempChar.length+1);
}
tempChar[i] = str[random.nextInt(str.length)];
tempChar[tempChar.length-1] =str[random.nextInt(str.length)];
}
}
}
return String.valueOf(tempChar);
}

欢迎指导并加以改进。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值