http://www.reibang.com/p/de903c074d77
https://blog.csdn.net/lizhengjava/article/details/76947962
開啟Google的登陸二步驗(yàn)證(即Google Authenticator服務(wù))后用戶登陸時(shí)需要輸入額外由手機(jī)客戶端生成的一次性密碼。
實(shí)現(xiàn)Google Authenticator功能需要服務(wù)器端和客戶端的支持。服務(wù)器端負(fù)責(zé)密鑰的生成、驗(yàn)證一次性密碼是否正確淹父∥棺撸客戶端記錄密鑰后生成一次性密碼蜕该。
目前客戶端有:
android版: Google 身份驗(yàn)證器
iOS版:https://itunes.apple.com/cn/app/google-authenticator/id388497605
實(shí)現(xiàn)原理:
一蔗彤、用戶需要開啟Google Authenticator服務(wù)時(shí)俩莽,
1.服務(wù)器隨機(jī)生成一個(gè)類似于『DPI45HKISEXU6HG7』的密鑰旺坠,并且把這個(gè)密鑰保存在數(shù)據(jù)庫中。
2.在頁面上顯示一個(gè)二維碼扮超,內(nèi)容是一個(gè)URI地址(otpauth://totp/賬號(hào)?secret=密鑰)取刃,如『otpauth://totp/kisexu@gmail.com?secret=DPI45HCEBCJK6HG7』,下圖:
otpauth://totp/kisexu@gmail.com?secret=DPI45HCEBCJK6HG7 (二維碼自動(dòng)識(shí)別)
3.客戶端掃描二維碼出刷,把密鑰『DPI45HKISEXU6HG7』保存在客戶端璧疗。
二、用戶需要登陸時(shí)
1.客戶端每30秒使用密鑰『DPI45HKISEXU6HG7』和時(shí)間戳通過一種『算法』生成一個(gè)6位數(shù)字的一次性密碼馁龟,如『684060』崩侠。如下圖android版界面:
2.用戶登陸時(shí)輸入一次性密碼『684060』。
3.服務(wù)器端使用保存在數(shù)據(jù)庫中的密鑰『DPI45HKISEXU6HG7』和時(shí)間戳通過同一種『算法』生成一個(gè)6位數(shù)字的一次性密碼坷檩。大家都懂控制變量法啦膜,如果算法相同、密鑰相同淌喻,又是同一個(gè)時(shí)間(時(shí)間戳相同)僧家,那么客戶端和服務(wù)器計(jì)算出的一次性密碼是一樣的。服務(wù)器驗(yàn)證時(shí)如果一樣裸删,就登錄成功了八拱。
Tips:
1.這種『算法』是公開的,所以服務(wù)器端也有很多開源的實(shí)現(xiàn)涯塔,比如php版的:https://github.com/PHPGangsta/GoogleAuthenticator 肌稻。上github搜索『Google Authenticator』可以找到更多語言版的Google Authenticator。
2.所以匕荸,你在自己的項(xiàng)目可以輕松加入對(duì)Google Authenticator的支持爹谭,在一個(gè)客戶端上顯示多個(gè)賬戶的效果可以看上面android版界面的截圖。目前dropbox榛搔、lastpass诺凡、wordpress,甚至vps等第三方應(yīng)用都支持Google Authenticator登陸践惑,請(qǐng)自行搜索腹泌。
3.現(xiàn)實(shí)生活中,網(wǎng)銀尔觉、網(wǎng)絡(luò)游戲的實(shí)體動(dòng)態(tài)口令牌其實(shí)原理也差不多凉袱,
//Google Authenticator
// 只從google出了雙重身份驗(yàn)證后,就方便了大家,等同于有了google一個(gè)級(jí)別的安全专甩,但是我們?cè)撛趺词褂胓oogle authenticator (雙重身份驗(yàn)證)钟鸵,
//下面是java的算法,這樣大家都可以得到根據(jù)key得到公共的秘鑰了,直接復(fù)制涤躲,記得導(dǎo)入JAR包:
//
//commons-codec-1.8.jar
//
//junit-4.10.jar
//測(cè)試方法:
//
//1棺耍、執(zhí)行測(cè)試代碼中的“genSecret”方法,將生成一個(gè)KEY(用戶為testuser)篓叶,URL打開是一張二維碼圖片烈掠。
//
//2、在手機(jī)中下載“GOOGLE身份驗(yàn)證器”缸托。
//
//3左敌、在身份驗(yàn)證器中配置賬戶,輸入賬戶名(第一步中的用戶testuser)俐镐、密鑰(第一步生成的KEY)矫限,選擇基于時(shí)間。
//
//4佩抹、運(yùn)行authcode方法將key和要測(cè)試的驗(yàn)證碼帶進(jìn)去(codes叼风,key),就可以知道是不是正確的秘鑰了棍苹!返回值布爾
jar
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
GoogleAuthenticator
public class GoogleAuthenticator {
// taken from Google pam docs - we probably don't need to mess with these
public static final int SECRET_SIZE = 10;
public static final String SEED = "g8GjEvTbW5oVSV7avLBdwIHqGlUYNzKFI7izOF8GwLDVKs2m0QN7vxRs2im5MDaNCWGmcD2rvcZx";
public static final String RANDOM_NUMBER_ALGORITHM = "SHA1PRNG";
int window_size = 3; // default 3 - max 17 (from google docs)最多可偏移的時(shí)間
public void setWindowSize(int s) {
if (s >= 1 && s <= 17)
window_size = s;
}
public static Boolean authcode(String codes, String savedSecret) {
// enter the code shown on device. Edit this and run it fast before the
// code expires!
long code = Long.parseLong(codes);
long t = System.currentTimeMillis();
GoogleAuthenticator ga = new GoogleAuthenticator();
ga.setWindowSize(15); // should give 5 * 30 seconds of grace...
boolean r = ga.check_code(savedSecret, code, t);
return r;
}
public static String genSecret(String user) {
String secret = GoogleAuthenticator.generateSecretKey();
GoogleAuthenticator.getQRBarcodeURL(user,
"testhost", secret);
return secret;
}
public static String generateSecretKey() {
SecureRandom sr = null;
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);
String encodedKey = new String(bEncodedKey);
return encodedKey;
}catch (NoSuchAlgorithmException e) {
// should never occur... configuration error
}
return null;
}
public static String getQRBarcodeURL(String user, String host, String secret) {
String format = "https://www.google.com/chart?chs=200x200&chld=M%%7C0&cht=qr&chl=otpauth://totp/%s@%s%%3Fsecret%%3D%s";
return String.format(format, user, host, secret);
}
public 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());
//return false;
}
if (hash == code) {
return true;
}
}
// The validation code is invalid.
return false;
}
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;
}
}
1,調(diào)用 genSecret 方法 生成key
@RestController
@RequestMapping
public class Controller {
//第一步生成key
@RequestMapping("/pic")
public String pic(String user){
String key= GoogleAuthenticator.genSecret(user);
//......省略保存到redis和數(shù)據(jù)庫的方法 user/key
}
//第二步无宿,請(qǐng)求接口生成二維碼圖片
前臺(tái)傳入用戶名,根據(jù)用戶名獲取 第一步生成的 key生成二維碼圖片
public String index(String user){
//...省略獲取 key 方法,讀取數(shù)據(jù)庫或redis
String key=null;
//根據(jù)key 和user 拼接成鏈接 content,在調(diào)一批能夠方法生成二維碼
String content="otpauth://totp/"+user+"?"+"secret="+key;
return qrcode(content);//調(diào)用 qrcode 方法 枢里,形成二維碼圖片孽鸡,返回給前端
}
public void qrcode(String content, @RequestParam(defaultValue = "300", required = false) int width,@RequestParam(defaultValue = "300", required = false) int height, HttpServletResponse response) {
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
QRCodeUtil.writeToStream(content, outputStream, width, height);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//頁面登錄校驗(yàn),輸入用戶名和谷歌驗(yàn)證碼栏豺,去校驗(yàn)谷歌驗(yàn)證碼是否正確 true/false
@RequestMapping("/authcode")
public boolean authcode(String user,String codes){
//通過用戶名獲取key彬碱;
String key="CS2KGNLIYETWRHO3";
return GoogleAuthenticator.authcode(codes,key);//校驗(yàn)谷歌驗(yàn)證碼是否正確
}
}
QRCodeUtil
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
/**
* 二維碼工具類
*/
public class QRCodeUtil {
private static final int width = 300;// 默認(rèn)二維碼寬度
private static final int height = 300;// 默認(rèn)二維碼高度
private static final String format = "png";// 默認(rèn)二維碼文件格式
private static final Map<EncodeHintType, Object> hints = new HashMap();// 二維碼參數(shù)
static {
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 字符編碼
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 容錯(cuò)等級(jí) L、M奥洼、Q巷疼、H 其中 L 為最低, H 為最高
hints.put(EncodeHintType.MARGIN, 2);// 二維碼與圖片邊距
}
/**
* 返回一個(gè) BufferedImage 對(duì)象
* @param content 二維碼內(nèi)容
* @param width 寬
* @param height 高
*/
public static BufferedImage toBufferedImage(String content, int width, int height) throws WriterException, IOException {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
/**
* 將二維碼圖片輸出到一個(gè)流中
* @param content 二維碼內(nèi)容
* @param stream 輸出流
* @param width 寬
* @param height 高
*/
public static void writeToStream(String content, OutputStream stream, int width, int height) throws WriterException, IOException {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToStream(bitMatrix, format, stream);
}
/**
* 生成二維碼圖片文件
* @param content 二維碼內(nèi)容
* @param path 文件保存路徑
* @param width 寬
* @param height 高
*/
public static void createQRCode(String content, String path, int width, int height) throws WriterException, IOException {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
//toPath() 方法由 jdk1.7 及以上提供
MatrixToImageWriter.writeToPath(bitMatrix, format, new File(path).toPath());
}
}