Java验证码的生成方法有哪些

avatar
作者
猴君
阅读量:0

  1. 使用Java自带的Random类生成随机数
import java.util.Random;  public String generateCaptcha(int length) {     StringBuilder captcha = new StringBuilder();     Random random = new Random();     for (int i = 0; i < length; i++) {         captcha.append(random.nextInt(10));     }     return captcha.toString(); } 
  1. 使用Apache Commons库生成随机字符串
import org.apache.commons.text.RandomStringGenerator;  public String generateCaptcha(int length) {     RandomStringGenerator generator = new RandomStringGenerator.Builder()             .withinRange('0', '9')             .build();     return generator.generate(length); } 
  1. 使用SecureRandom类生成安全的随机数
import java.security.SecureRandom; import java.util.Base64;  public String generateCaptcha(int length) {     SecureRandom random = new SecureRandom();     byte[] bytes = new byte[length];     random.nextBytes(bytes);     return Base64.getEncoder().encodeToString(bytes).substring(0, length); } 
  1. 使用UUID生成唯一的验证码
import java.util.UUID;  public String generateCaptcha() {     String uuid = UUID.randomUUID().toString().replaceAll("-", "");     return uuid.substring(0, 6); } 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!