1 package org.micro.service.springboot;
2
3 import java.util.Random;
4
5 /**
6 * @author: ChenYan
7 * @date: 2019年4月24日
8 * @description: 生成验证码
9 */
10 public class ValidCodeUtils {
11
12 private static char[] numbers = "0123456789".toCharArray();
13
14 private static char[] words = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ".toCharArray();
15
16 private static final int MIN_LEN = 4;
17
18 private static final int MAX_LEN = 8;
19
20 /**
21 * @author: ChenYan
22 * @date: 2019年4月24日
23 * @param len
24 * @return
25 * @description: 返回数字验证码
26 */
27 public static String generateNumber(int len) {
28 len = limitLen(len);
29 Random random = new Random();
30 char[] cs = new char[len];
31 for (int i = 0; i < cs.length; i++) {
32 cs[i] = numbers[random.nextInt(numbers.length)];
33 }
34 return new String(cs);
35 }
36
37 /**
38 * @author: ChenYan
39 * @date: 2019年4月24日
40 * @param len
41 * @return
42 * @description: 返回字符数字混合型验证码
43 */
44 public static String generateCode(int len) {
45 len = limitLen(len);
46 Random random = new Random();
47 char[] cs = new char[len];
48 for (int i = 0; i < cs.length; i++) {
49 cs[i] = words[random.nextInt(words.length)];
50 }
51 return new String(cs);
52 }
53
54 /**
55 * @author: ChenYan
56 * @date: 2019年4月24日
57 * @param len
58 * @return
59 * @description: 限制验证码长度
60 */
61 private static int limitLen(int len) {
62 if (len < MIN_LEN) {
63 return MIN_LEN;
64 } else if (len > MAX_LEN) {
65 return MAX_LEN;
66 } else {
67 return len;
68 }
69 }
70
71 public static void main(String[] args) {
72 String code=ValidCodeUtils.generateCode(6);
73 System.out.println("code===="+code);
74 String number=ValidCodeUtils.generateNumber(6);
75 System.out.println("number===="+number);
76 }
77 }
