生成随机字符串(密码)

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

package com.xingsfdz.util;

import java.util.Random;

/**
 * 
 * @类名称 StringUtils.java
 * @类描述 <pre></pre>
 * @作者  xingsfdz xingsfdz@163.com
 * @创建时间 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);
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值