常常在输入验证码时,都是简单的字母+ 数字,而汉字则相对较少。 相关知识,汉字编码原理
汉字验证码
import java.util.*;
public class CheckCode {
public static void main(String[] args) {
String code = "";
Random random = new Random();
String[] rBase = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"a", "b", "c", "d", "e", "f" };
// 生成第1位的区码
int r1 = random.nextInt(3) + 11; // 生成11到14之间的随机数
String str_r1 = rBase[r1];
// 生成第2位的区码
int r2;
if (r1 == 13) {
r2 = random.nextInt(7); // 生成0到7之间的随机数
} else {
r2 = random.nextInt(16); // 生成0到16之间的随机数
}
String str_r2 = rBase[r2];
// 生成第1位的位码
int r3 = random.nextInt(6) + 10; // 生成10到16之间的随机数
String str_r3 = rBase[r3];
// 生成第2位的位码
int r4;
if (r3 == 10) {
r4 = random.nextInt(15) + 1; // 生成1到16之间的随机数
} else if (r3 == 15) {
r4 = random.nextInt(15); // 生成0到15之间的随机数
} else {
r4 = random.nextInt(16); // 生成0到16之间的随机数
}
String str_r4 = rBase[r4];
System.out.println(str_r1 + str_r2 + str_r3 + str_r4);
// 将生成机内码转换为汉字
byte[] bytes = new byte[2];
// 将生成的区码保存到字节数组的第1个元素中
String str_r12 = str_r1 + str_r2;
int tempLow = Integer.parseInt(str_r12, 16);
bytes[0] = (byte) tempLow;
// 将生成的位码保存到字节数组的第2个元素中
String str_r34 = str_r3 + str_r4;
int tempHigh = Integer.parseInt(str_r34, 16);
bytes[1] = (byte) tempHigh;
code = new String(bytes); // 根据字节数组生成汉字
System.out.println("生成汉字:" + code);
}
}