Java

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

小樊
88
2024-08-09 08:46:36
栏目: 编程语言

  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);
}

0
看了该问题的人还看了