動態生成google 身份驗證碼(口令)

依賴

<!-- 谷歌驗證碼 -->
		<dependency>
			<groupId>com.warrenstrange</groupId>
			<artifactId>googleauth</artifactId>
			<version>1.2.0</version>
		</dependency>

場景:

驗證身份

一般是重要的網站或平臺 需要在登錄的時候強校驗身份, 每個用戶綁定一個 安全碼,這個碼 會根據時間變化生成不同的驗證碼,只有該用戶掌握了對應的安全碼,綁定在 google 身份驗證器app 中,可以查詢到,然後與後臺算法生成的進行對比,驗證身份

具體代碼:

package com.util;

import com.warrenstrange.googleauth.GoogleAuthenticator;
import com.warrenstrange.googleauth.GoogleAuthenticatorKey;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 增加google 動態驗證碼工具類
 * 增加googleauth-1.1.2.jar
 *
 * account,會員賬號, secret 安全碼, issuer 服務名稱,如印象筆記等,  除了安全碼非空外,都可爲空
 * Google Authenticator 約定的二維碼信息格式 : otpauth://totp/{account}?secret={secret}&issuer={issuer}
 */
public class GoogleAuth {


    public static void main(String[] args) {
        String key = getKeyStr();//P3IBV7BGUR3BKVCL //2TRXIQBK3SGJ5EQN
//        String key = "P3IBV7BGUR3BKVCL";//16 位由Base32 的密碼組成的服務碼
////        int code = getVercode(key);
////        boolean isPattern = isPattern(key,code);
    }


    /**
     * 防止生成重複安全碼
     * @param list      已生成的安全碼
     * @return
     */
    public static String getRepetitionKeyStr(List<String> list) {
        AtomicInteger integer = new AtomicInteger(0);
        String code = "";
        while (integer.get() < 1) {
            code = getKeyStr();
            if((null == list || list.size() == 0) || !list.contains(code)) {
                integer.incrementAndGet();//原子自增
            }
        }
        return code;
    }

    /**
     * 獲得爲用戶隨機生成的安全碼
     * @return
     */
    public static String getKeyStr() {
        GoogleAuthenticator gAuth  = new GoogleAuthenticator();
        final GoogleAuthenticatorKey key = gAuth .createCredentials();
        String keyStr = key.getKey();
//        System.out.println(keyStr);
        return keyStr;
    }

    /**
     * 判斷輸入的驗證碼是否符合
     * @param key        安全碼
     * @param password   驗證碼,根據時間來生成的驗證碼
     * @return
     */
    public static boolean isPattern(String key,int password) {
        GoogleAuthenticator gAuth = new GoogleAuthenticator();
        boolean isPattern = gAuth.authorize(key,password);
//        System.out.println(isPattern);
        return isPattern;
    }


    /**
     * 獲得TOTF算法生成的驗證碼,根據時間產生
     * @param secretKey   安全碼
     * @return
     */
    public static int getVercodeTime(String secretKey) {
        GoogleAuthenticator gAuth = new GoogleAuthenticator();
        int code = gAuth.getTotpPassword(secretKey);
//        System.out.println(code);
        return code;
    }



}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章