生成随机字符串(密码)

直接上代码,根据传入的长度生成(且密码中必须包含数字,大小写字母)

package com.xingsfdz.util;

import java.util.Random;

/**
 * 
 * @类名称 StringUtils.java
 * @类描述 <pre></pre>
 * @作者  xingsfdz [email protected]
 * @创建时间 2019年9月26日 下午9:47:35
 * @版本 1.00
 *
 * @修改记录
 * <pre>
 *     版本                       修改人 		修改日期 		 修改内容描述
 *     ----------------------------------------------
 *     1.00 	xingsfdz 	2019年9月26日             
 *     ----------------------------------------------
 * </pre>
 */
public class StringUtils {

	/**
	 * 
	 * @方法名称 GenRandomStringByLen
	 * @功能描述 <pre>生成传入的长度的密码</pre>
	 * @作者    xingsfdz
	 * @创建时间 2019年9月26日 下午10:39:03
	 * @param len
	 * @return
	 */
	public static String GenRandomStringByLen(Integer len){
		String password = "";
		
		int[] pwdindex =new int[len];
		
		char[] numbers = { '0','1','2','3','4','5','6','7','8','9'};
		
		char[] upperLetters = {'A','B','C','D','E','F','G','H','I','J',
				'K','L','M','N','O','P','Q','R','S','T',
				'U','V','W','X','Y','Z'};
		
		char[] lowerLetters = {'a','b','c','d',
				'e','f','g','h','i','j','k','l','m','n',
				'o','p','q','r','s','t','u','v','w','x',
				'y','z'};
		
		
		char[] allCharacters = { '0','1','2','3','4','5','6','7','8','9',
				'A','B','C','D','E','F','G','H','I','J',
				'K','L','M','N','O','P','Q','R','S','T',
				'U','V','W','X','Y','Z','a','b','c','d',
				'e','f','g','h','i','j','k','l','m','n',
				'o','p','q','r','s','t','u','v','w','x',
				'y','z'};
		
		StringBuilder sb = new StringBuilder();
				
		for (int i = 0; i < pwdindex.length; i++) {
			sb.append(allCharacters[new Random().nextInt(62)]);
		}
		password = sb.toString();//先按传进来的长度生成一个随机密码
		//下面处理密码中必须包含大小写字母与数字
		int a = 0;
		int b = 0;
		int c = 0;
		a = new Random().nextInt(len);
		while(a == b){
			b = new Random().nextInt(len);
		}
		while(a == c || b == c){
			c = new Random().nextInt(len);
		}
		password = password.replace(password.charAt(a), lowerLetters[new Random().nextInt(26)]);//小写
		password = password.replace(password.charAt(b), numbers[new Random().nextInt(10)]);//数字
		password = password.replace(password.charAt(c), upperLetters[new Random().nextInt(26)]);//大写
		System.out.println("password:" + password);
		return password;
	}
	
	public static void main(String[] args) {
			GenRandomStringByLen(3);
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章