1. 程式人生 > >Java工具類-驗證碼工具

Java工具類-驗證碼工具

 

1.工具類,生成隨機驗證碼字串

import java.util.Arrays;

/**
 * 工具類,生成隨機驗證碼字串
 * 
 * @version 1.0
 * @author
 * 
 */

public class SecurityCode {
    /**
     * 驗證碼難度級別,Simple只包含數字,Medium包含數字和小寫英文,Hard包含數字和大小寫英文
     */
    public enum SecurityCodeLevel {
        Simple, Medium, Hard
    };

    
/** * 產生預設驗證碼,4位中等難度 * * @return String 驗證碼 */ public static String getSecurityCode() { return getSecurityCode(4, SecurityCodeLevel.Medium, false); } /** * 產生長度和難度任意的驗證碼 * * @param length * 長度 * @param level * 難度級別 *
@param isCanRepeat * 是否能夠出現重複的字元,如果為true,則可能出現 5578這樣包含兩個5,如果為false,則不可能出現這種情況 * @return String 驗證碼 */ public static String getSecurityCode(int length, SecurityCodeLevel level, boolean isCanRepeat) { // 隨機抽取len個字元 int len = length;
// 字元集合(除去易混淆的數字0、數字1、字母l、字母o、字母O) char[] codes = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; // 根據不同的難度擷取字元陣列 if (level == SecurityCodeLevel.Simple) { codes = Arrays.copyOfRange(codes, 0, 9); } else if (level == SecurityCodeLevel.Medium) { codes = Arrays.copyOfRange(codes, 0, 33); } // 字元集合長度 int n = codes.length; // 丟擲執行時異常 if (len > n && isCanRepeat == false) { throw new RuntimeException(String.format( "呼叫SecurityCode.getSecurityCode(%1$s,%2$s,%3$s)出現異常," + "當isCanRepeat為%3$s時,傳入引數%1$s不能大於%4$s", len, level, isCanRepeat, n)); } // 存放抽取出來的字元 char[] result = new char[len]; // 判斷能否出現重複的字元 if (isCanRepeat) { for (int i = 0; i < result.length; i++) { // 索引 0 and n-1 int r = (int) (Math.random() * n); // 將result中的第i個元素設定為codes[r]存放的數值 result[i] = codes[r]; } } else { for (int i = 0; i < result.length; i++) { // 索引 0 and n-1 int r = (int) (Math.random() * n); // 將result中的第i個元素設定為codes[r]存放的數值 result[i] = codes[r]; // 必須確保不會再次抽取到那個字元,因為所有抽取的字元必須不相同。 // 因此,這裡用陣列中的最後一個字元改寫codes[r],並將n減1 codes[r] = codes[n - 1]; n--; } } return String.valueOf(result); } public static void main(String[] args) { SecurityCode code = new SecurityCode(); System.out.println(getSecurityCode(6,SecurityCodeLevel.Hard,false)); } }