随机密码
1. 随机密码 : 6位数字
public static String randompassword(){
char[] chars = new char[6];
Random rnd = new Random();
for(int i=0;i < 6 ; i++){
chars[i] = (char)('0'+rnd.nextInt(10));
}
return new String(chars);
}
2. 随机密码 : 8位密码,但是包括字符,和特殊符合
private static final String SPECIAL_CHARS = “!@#$^&*_=+/”;
private static char nextChar(Random rnd){
switch(rnd.nextInt(4)){
case 0:
return (char)('a'+rnd.nextInt(26));
case 1:
return (char)('A'+rnd.nextInt(26));
case 2:
return (char)('0'+rnd.nextInt(10));
default :
return String SPECIAL_CHARS.charAt(rnd.nextInt(String SPECIAL_CHARS.length()));
}
}
public static String randomPassword(){
char[] chars = new char(8);
Random rnd = new Random();
for(int i=0; i < 8 ; i++){
chars[i] = nextChar(rnd);
}
return new String(chars);
}
3. 随机密码 : 复杂8位
private static int nextIndex(char[] chars, Random rnd){
int index= rnd.nextInt(chars.length);
while(chars[index] != 0){
index = rnd.nextInt(chars.length);
}
return index;
}
private static char nextSecialChar(Random rnd){
return String SPECIAL_CHARS.charAt(rnd.nextInt(String SPECIAL_CHARS.length()));
}
private static char nextUpperLetter(Random rnd){
return (char)('A' + rnd.nextInt(26));
}
private static char nextLowerLetter(Random rnd){
return (char)('0' + rnd.nextInt(10));
}
public static String randomPassword(){
char[] chars = new char[8];
Random rnd = new Random();
chars[nextIndex(chars,rnd)] = nextSpecialChar(rnd);
chars[nextIndex(chars,rnd)] = nextUpperLetter(rnd);
chars[nextIndex(chars,rnd)] = nextLowerLetter(rnd);
chars[nextIndex(chars,rnd)] = nextNumLetter(rnd);
for(int i=0l i< 8 ; i++){
if(chars[i] == 0){
chars[i] = nextChar(rnd);
}
}
return new String(chars);
}
4. 随机的基本原理
- Random产生的随机数不是真正的随机数,相反,他产生的随机数一般为伪随机数,真正的随机数比较难以产生,计算机程序中的随机数一般都是伪随机数
- 伪随机数 是基于一个种子数 的,然后需要一个随机数,然后对当前种子进行一些数学运算,而得到新的随机数和新的种子
- 在Random 中 随机数 不是真正的随机数,但是 种子 是一个真正的随机数。
- java8 中看到
private static long seedUniquifier() {
for (;;) {
long current = seedUniquifier.get();
long next = current * 181783497276652981L;
if (seedUniquifier.compareAndSet(current, next))
return next;
}
}
- 种子 是seedUniquifier 和 System.nanoTime 按位异或的结果
System.nanoTime 返回一个更高精度的当前时间(纳秒) - 通过next 来生成指定位数的随机数
protected int next(int bits) {
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) & mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}
- 就是使用这个公式
nextSeed = (oldseed * multiplier + addend) & mask ;
- 上面的方法 叫 线性同余随机数生成器
- 通过 上面的方法,相同的就是 洗牌 和带权重的随机选择,,都可以这样 写出