java生成漢字驗證碼
常常在輸入驗證碼時,都是簡單的字母+ 數字,而漢字則相對較少。 相關知識,漢字編碼原理
漢字驗證碼
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); }
} </pre>
本文由用戶 lplo 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!