- 使用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(); }
- 使用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); }
- 使用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); }
- 使用UUID生成唯一的验证码
import java.util.UUID; public String generateCaptcha() { String uuid = UUID.randomUUID().toString().replaceAll("-", ""); return uuid.substring(0, 6); }