現在很多應用的驗證碼採用的中文驗證碼,一定程度的放大了OCR之類的圖像識別破解驗證碼的難度,原理主要是中文編碼的生成格式,規定兩個127以後的字節組合在一起形成一個漢字,前面的一個字節(高位)從0xA1到0xF7,後面的一個字節(低位)從0xA1到0xFE。這樣就能組成7000多個簡體漢字。
爲了去掉生僻字,選取高位176到215,低位161到254,保留下來3600多個常用字.
代碼實現如下:
public class CreateCheckCode {
/**
* 生成隨機漢字
* @return
*/
public static char getRandomChar() {
String str = "";
int hightPos;
int lowPos;
Random random = new Random();
hightPos = (176 + Math.abs(random.nextInt(39)));
lowPos = (161 + Math.abs(random.nextInt(93)));
byte[] b = new byte[2];
b[0] = (Integer.valueOf(hightPos)).byteValue();
b[1] = (Integer.valueOf(lowPos)).byteValue();
try {
str = new String(b, "GB2312");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str.charAt(0);
}
public static void main(String[] args) {
char[] words = new char[4];
for (int i = 0; i<words.length; i++) {
words[i] = getRandomChar();
}
System.out.println(words);
}
}
測試結果如下,運行代碼得到一個4個字的隨機漢字
: