0
点赞
收藏
分享

微信扫一扫

java测试生成中征码(包含字母、数字)


public static void main(String[] args) {
String val =genSixToSixteenPsw();
System.out.println("企业中征码为:" + val);
}

/**
* 随机14位中证码
* @return
*/
public static String genSixToSixteenPsw() {
String val = "";
Random random = new Random();
//长度14位
int numbers = 14;
for (int i = 0; i < numbers; i++) {
// 输出字母还是数字
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
// 字符串
if ("char".equalsIgnoreCase(charOrNum)) {
//取得大写字母还是小写字母
int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
val += (char) (choice + random.nextInt(26));
} else if ("num".equalsIgnoreCase(charOrNum)) {
// 数字
val += String.valueOf(random.nextInt(10));
}
}
return checkZZM(val.toUpperCase());
}

//校验中征码
public static String checkZZM(String value) {
//判断中征码前14位
if (value.length()!=14) {
return "";
}
//前14位转化为char数组
char[] idCode = value.substring(0, 14).toCharArray();
//加权因子
int[] weight_factor = new int[]{1, 3, 5, 7, 11, 2, 13, 1, 1, 17, 19, 97, 23, 29};
int len = idCode.length;
int num = 0;
int temp = 0;
//循环取和
for (int i = 0; i < len; i++) {
//字母转数字
if (idCode[i] >= 'A' && idCode[i] <= 'Z') {
temp = (int) idCode[i] - 55;
} else {
temp = (int) idCode[i] - 48;
}
//求和
num = num + temp * weight_factor[i];
}
//取余+1
int resisue = num % 97 + 1;
System.out.println("生成2位验证码为:"+resisue);
//拼接验证码
value = value + resisue;
//判断中征码是否为16位
if (value.length()!=16) {
return "";
}
return value;
}


举报

相关推荐

0 条评论