随机生成验证码(忘记参考地址)

import java.util.Random;

/**

  • @Description 随机生成验证码
  • @Author nice
  • @Date 2021/8/17 4:06 下午
    */

public class VerifyCodeUtils {

public static final String VERIFY_CODES = "23456789abcdefghjklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
private static Random random = new Random();


/**
 * 使用系统默认字符源生成验证码
 * @param verifySize    验证码长度
 * @return
 */
public static String generateVerifyCode(int verifySize){
    return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
 * 使用指定源生成验证码
 * @param verifySize    验证码长度
 * @param sources   验证码字符源
 * @return
 */
public static String generateVerifyCode(int verifySize, String sources){
    if(sources == null || sources.length() == 0){
        sources = VERIFY_CODES;
    }
    int codesLen = sources.length();
    Random rand = new Random(System.currentTimeMillis());
    StringBuilder verifyCode = new StringBuilder(verifySize);
    for(int i = 0; i < verifySize; i++){
        verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
    }
    return verifyCode.toString();
}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容