在帳戶安全體系中,很常見的有手機驗證,郵箱驗證,谷歌二次驗證。今天重點畫下谷歌二次驗證也就是Google Authenticator的開發使用。Google Authenticator不僅安全可靠,還可以離線使用,即使終端沒有網絡的情況下也可以進行驗證。銀行的U盾也是使用同樣的方式。在這裏不進行二次驗證的原理說明,有興趣的同學可以到 Google賬戶兩步驗證的工作原理 進行了解哈。
驗證器的終端使用之一如圖,每三十秒會變換一次六位隨機數。
接下來我們進行java後端如何接入二次驗證。只需要一個GoogleAuthenticator類就搞定。是基於時間的驗證算法。注意需要導入依賴commons-codec 1.10,maven的導入如下:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
GoogleAuthenticator類代碼,可直接複製到項目中使用
public class GoogleAuthenticator {
// 來自谷歌文檔,不用修改
public static final int SECRET_SIZE = 10;
// 產生密鑰的種子
public static final String SEED = "N%U%cls36e7Ab!@#asd34nB4%9%Nmo2ai1IC9@54n06aY";
// 安全哈希算法(Secure Hash Algorithm)
public static final String RANDOM_NUMBER_ALGORITHM = "SHA1PRNG";
//可偏移的時間 -- 3*30秒的驗證時間(客戶端30秒生成一次驗證碼)
private static Integer window_size = 3;
/**
* 生成密鑰
*
* @return
*/
public static String generateSecretKey() {
SecureRandom sr;
try {
sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM);
sr.setSeed(Base64.decodeBase64(SEED));
byte[] buffer = sr.generateSeed(SECRET_SIZE);
Base32 codec = new Base32();
byte[] bEncodedKey = codec.encode(buffer);
return new String(bEncodedKey);
} catch (NoSuchAlgorithmException e) {
// should never occur... configuration error
}
return null;
}
/**
* 校驗驗證碼
*
* @param secret
* @param code
* @param timeMsec
* @return
*/
public static Boolean check_code(String secret, long code, long timeMsec) {
Base32 codec = new Base32();
byte[] decodedKey = codec.decode(secret);
// convert unix msec time into a 30 second "window"
// this is per the TOTP spec (see the RFC for details)
long t = (timeMsec / 1000L) / 30L;
// Window is used to check codes generated in the near past.
// You can use this value to tune how far you're willing to go.
for (int i = -window_size; i <= window_size; ++i) {
long hash;
try {
hash = verify_code(decodedKey, t + i);
} catch (Exception e) {
// Yes, this is bad form - but
// the exceptions thrown would be rare and a static configuration problem
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
if (hash == code) {
return true;
}
}
// The validation code is invalid.
return false;
}
/**
* 生成驗證碼
*
* @param key
* @param t
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
private static int verify_code(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException {
byte[] data = new byte[8];
long value = t;
for (int i = 8; i-- > 0; value >>>= 8) {
data[i] = (byte) value;
}
SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signKey);
byte[] hash = mac.doFinal(data);
int offset = hash[20 - 1] & 0xF;
// We're using a long because Java hasn't got unsigned int.
long truncatedHash = 0;
for (int i = 0; i < 4; ++i) {
truncatedHash <<= 8;
// We are dealing with signed bytes:
// we just keep the first byte.
truncatedHash |= (hash[offset + i] & 0xFF);
}
truncatedHash &= 0x7FFFFFFF;
truncatedHash %= 1000000;
return (int) truncatedHash;
}
}
生成驗證碼
如果用戶是要進行綁定二次驗證的話,使用 generateSecretKey() 方法生成密鑰,返回給用戶,用戶使用這個密鑰在驗證器終端進行綁定,就可以獲取六位數字。此方法返回的是字符串,用戶只能手動輸入的。也可以生成一個二維碼,用驗證器終端掃。
生成二維碼的方式:
返回此格式的字符串,然後前端理由二維碼生成工具,生成二維碼即可。
"otpauth://totp/" + "胖子@csdn" + "?secret=" + key
注意 “胖子@csdn”是指該二次驗證的備註而已,可以用登錄名@產品名稱給用戶固定好。如上面的終端使用圖中的loginName@Core。key即是生成的密鑰,服務器需要保存好密鑰,在驗證的時候需要用到。
校驗驗證碼
直接調用 check_code 方法即可。參數分別爲 密鑰,六位驗證碼,當前時間戳。如
check_code("GWBDN7GSV5OBFMPN", Long.valueOf("380168"), System.currentTimeMillis())
後端根據返回的 true or false 進行業務邏輯判斷操作即可。
谷歌二次驗證的開發就是這麼簡單的使用就可以啦,是不是很激動,趕緊到自己的項目中嘗試嘗試哈哈哈。如有問題可以留言,博主看到了會回覆的哈。有建議也可以聯繫博主哦,博主也是很喜歡學習的。謝謝大家,不喜勿噴呀...