求一个java密码随机生成程序 5C

要求:同时含有大小写字母,数字,特殊字符但不含有空格,8到32位,最好长度作为一个参数可调整

6个回答

import java.util.Random;

public class RandomPassword {

public static void main(String[] args) {

    String password = getRandomPassword(8);  
    System.out.println(password);  
}  

//获取验证过的随机密码  
public static String getRandomPassword(int len) {  
    String result = null;  

    /*if(len >= 6) { 
        for(result = makeRandomPassword(len);len >= 6;result = makeRandomPassword(len)){              
            if (result.matches(".*[a-z]{1,}.*") && result.matches(".*[A-Z]{1,}.*") && result.matches(".*\\d{1,}.*") && result.matches(".*[~!@#$%^&*\\.?]{1,}.*")) { 
                return result; 
            }  
        } 
    }*/  
    while(len>=6){  
        result = makeRandomPassword(len);  
        if (result.matches(".*[a-z]{1,}.*") && result.matches(".*[A-Z]{1,}.*") && result.matches(".*\\d{1,}.*") && result.matches(".*[~!@#$%^&*\\.?]{1,}.*")) {  
            return result;  
        }   
        result = makeRandomPassword(len);  
    }  
    return "长度不得少于6位!";  
}  
//随机密码生成  
public static String makeRandomPassword(int len){  
    char charr[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~!@#$%^&*.?".toCharArray();  
    //System.out.println("字符数组长度:" + charr.length); //可以看到调用此方法多少次  
    StringBuilder sb = new StringBuilder();  
    Random r = new Random();  

    for (int x = 0; x < len; ++x) {  
        sb.append(charr[r.nextInt(charr.length)]);  
    }  
    return sb.toString();  
}  

}

拿去随便改改

这个简单
class MyClass
private static Random rnd = new Random();
private String metachars = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ..."; //把你要的字符都写进去
public static String genPwd(int n)
{
String r = "";
for (int i = 0; i < n; i++) r += metachars.substring(rnd.nextInt(metachars.length() - 1), 1);
return r;
}
}

private static final byte INDEX_NUMBER = 0;
private static final byte INDEX_LETTER = 1;
private static final byte INDEX_SPECIAL_CHAR = 2;

/** 特殊符号 */
private static final char[] SPECIAL_CHARS = {'`','~','!','@','#','$','%','^','&','*','(',')','-','_','=','+','[',']','{','}','\\','|',';',':','\'','"',',','<','.','>','/','?'};

public static void main(String[] args) {
    int[] genChances = {1,2,3};
    char[] password = generateRandomPassword(5,genChances);
    System.out.println(password);
}

/**
 * 按一定的概率生成一个随机的N位(N>=3)密码,必须由字母数字特殊符号组成,三者缺一不可
 * @param len 密码长度,必须大于等于3
 * @param genChances 分别是生成数字、字母、特殊符号的概率
 * @return 生成的随机密码
 */
private static char[] generateRandomPassword(final int len,final int[] paramGenChances)throws IllegalArgumentException {
    if (len < 3) {
        throw new IllegalArgumentException("长度应该大于3");
    }
    final char[] password = new char[len];
    // 之所以该复制一份是为了使函数不对外产生影响
    final int[] genChances = paramGenChances.clone();
    final int[] genNums = new int[genChances.length];
    for (int i=0;i<genChances.length;i++){
        genNums[i] = 0;
    }
    final Random random = new Random();
    int r;
    for (int i = 0; i < len; i++) {
        adjustGenChance(len,i,genChances,genNums);
        int index = getPasswordCharType(random,genChances);
        genNums[index]++;
        switch (index) {
        case INDEX_NUMBER:
            password[i] = (char) ('0' + random.nextInt(10));
            break;
        case INDEX_LETTER:
            r = random.nextInt(52);
            if (r < 26) {
                password[i] = (char) ('A' + r);
            } else {
                password[i] = (char) ('a' + r - 26);
            }
            break;
        case INDEX_SPECIAL_CHAR:
            r = random.nextInt(SPECIAL_CHARS.length);
            password[i] = SPECIAL_CHARS[r];
            break;
        default:
            password[i] = ' ';
            break;
        }
    }
    return password;
}

/**
 * 根据当前需要生成密码字符的位置,动态调整生成概率
 * @param len 待生成的总长度
 * @param index 当前位置
 * @param genChances 分别是生成数字、字母、特殊符号的概率
 * @param genNums 这些类型已经生成过的次数
 */
private static void adjustGenChance(final int len,final int index,final int[] genChances,final int[] genNums) {
    final int leftCount = len - index;
    byte notGenCount = 0;
    for (int i = 0; i < genChances.length; i++) {
        if (genNums[i] == 0) {
            notGenCount++;
        }
    }
    if (notGenCount > 0 && leftCount < genChances.length && leftCount == notGenCount) {
        for (int i = 0; i < genChances.length; i++) {
            if (genNums[i] > 0) {
                genChances[i] = 0;
            }
        }
    }
}

/**
 * 获取该密码字符的类型
 * @param random 随机数生成器
 * @param genChances 分别是生成数字、字母、特殊符号的概率
 * @return 密码字符的类型
 */
private static int getPasswordCharType(final Random random, final int[] genChances) {
    int total = 0;
    int i = 0;
    for (; i < genChances.length; i++) {
        total += genChances[i];
    }
    int r = random.nextInt(total);
    for (i = 0; i < genChances.length; r -= genChances[i], i++) {
        if (r < genChances[i]) {
            break;
        }
    }
    return i;
}

想偷懒就先生成随机数,然后md5

public String CreateNonceStr() {
    int length = 16;
    String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    StringBuffer sb=new StringBuffer();
    Random rad = new Random();
    for (int i = 0; i < length; i++)
    {
        int number=rad.nextInt(chars.length());
        sb.append(chars.charAt(number));
    }
    return sb.toString();
}

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class PwdGenTest {

public static void main(String[] args) {
    PasswordGenerator pwdGen = new PasswordGenerator();
    for(int i = 0; i<20; ++i)
    {
        System.out.println(pwdGen.getPassword(12));
    }
}

}

class PasswordGenerator{

private int[] upperRange = {65, 90};
private int[] lowerRange = {97, 122};
private int[] digitalRange = {48,57};
private int[][] symbolRanges = {{33,47},{58,64}, {91,96}, {123,126}};

final static int CHAR_TYPE_UPPER = 0;
final static int CHAR_TYPE_LOWER = 1;
final static int CHAR_TYPE_DIGITAL = 2;
final static int CHAR_TYPE_SYMBOL = 3;
final static int[] CHAR_TYPES = {CHAR_TYPE_UPPER, CHAR_TYPE_LOWER, CHAR_TYPE_DIGITAL, CHAR_TYPE_SYMBOL};
final static int TYPE_COUNT = CHAR_TYPES.length;

private Random random = new Random();

public String getPassword(int length){
    int leftLength = length;
    List<Integer[]> typeLens = new ArrayList<Integer[]>();
    int i;
    for(i = 0; i < TYPE_COUNT - 1; ++i){
        int len = random.nextInt(leftLength-(TYPE_COUNT-i-1));
        typeLens.add(new Integer[]{CHAR_TYPES[i], len});
        leftLength -= len;
    }
    typeLens.add(new Integer[]{CHAR_TYPES[i], leftLength});

    int typeIndex = 0;
    Integer[] typeLen;
    StringBuilder builder = new StringBuilder();
    for(i = 0; i < length; ++i){
        typeIndex = random.nextInt(typeLens.size());
        typeLen = typeLens.get(typeIndex);
        switch(typeLen[0]){
        case CHAR_TYPE_UPPER:
            builder.append(getUpper());
            break;
        case CHAR_TYPE_LOWER:
            builder.append(getLower());
            break;
        case CHAR_TYPE_DIGITAL:
            builder.append(getDigital());
            break;
        default:
            builder.append(getSymbol());
            break;
        }
        --typeLen[1];
        if(typeLen[1] == 0)
            typeLens.remove(typeIndex);
    }
    return builder.toString();
}

private char getSymbol(){
    int symbolRangeIndex = random.nextInt(symbolRanges.length);
    return (char)(getRandomIntFromRange(symbolRanges[symbolRangeIndex][0], symbolRanges[symbolRangeIndex][1]));
}

private char getUpper(){
    return (char)(getRandomIntFromRange(upperRange[0], upperRange[1]));
}

private char getLower(){
    return (char)(getRandomIntFromRange(lowerRange[0], lowerRange[1]));
}

private char getDigital(){
    return (char)(getRandomIntFromRange(digitalRange[0], digitalRange[1]));
}

private int getRandomIntFromRange(int min, int max){
    return random.nextInt(max)%(max-min+1) + min;
}

}


自己写的,可能有更好的方法,但可以保证每次都全部包含你需要的字符种类,而且每种字符的位置长度随机。输出示例:
图片说明

ranyixu11
doggy_coder 看到输出不要以为是一串,每一行都是一个独立的12个字符的符合条件的密码,因为我循环了20次。
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问