60 Java 接入 Google Authenticator

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版界面:


image

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());
    }
}
















































最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市灵奖,隨后出現(xiàn)的幾起案子嚼沿,更是在濱河造成了極大的恐慌,老刑警劉巖桑寨,帶你破解...
    沈念sama閱讀 221,576評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件伏尼,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡尉尾,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門燥透,熙熙樓的掌柜王于貴愁眉苦臉地迎上來沙咏,“玉大人辨图,你說我怎么就攤上這事≈辏” “怎么了故河?”我有些...
    開封第一講書人閱讀 168,017評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)吆豹。 經(jīng)常有香客問我鱼的,道長(zhǎng),這世上最難降的妖魔是什么痘煤? 我笑而不...
    開封第一講書人閱讀 59,626評(píng)論 1 296
  • 正文 為了忘掉前任凑阶,我火速辦了婚禮,結(jié)果婚禮上衷快,老公的妹妹穿的比我還像新娘宙橱。我一直安慰自己,他們只是感情好蘸拔,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,625評(píng)論 6 397
  • 文/花漫 我一把揭開白布师郑。 她就那樣靜靜地躺著,像睡著了一般调窍。 火紅的嫁衣襯著肌膚如雪宝冕。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,255評(píng)論 1 308
  • 那天邓萨,我揣著相機(jī)與錄音地梨,去河邊找鬼。 笑死先誉,一個(gè)胖子當(dāng)著我的面吹牛湿刽,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播褐耳,決...
    沈念sama閱讀 40,825評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼诈闺,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了铃芦?” 一聲冷哼從身側(cè)響起雅镊,我...
    開封第一講書人閱讀 39,729評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎刃滓,沒想到半個(gè)月后仁烹,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,271評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡咧虎,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,363評(píng)論 3 340
  • 正文 我和宋清朗相戀三年卓缰,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,498評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡征唬,死狀恐怖捌显,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情总寒,我是刑警寧澤扶歪,帶...
    沈念sama閱讀 36,183評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站摄闸,受9級(jí)特大地震影響善镰,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜年枕,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,867評(píng)論 3 333
  • 文/蒙蒙 一炫欺、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧画切,春花似錦竣稽、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至典格,卻和暖如春岛宦,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背耍缴。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工砾肺, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人防嗡。 一個(gè)月前我還...
    沈念sama閱讀 48,906評(píng)論 3 376
  • 正文 我出身青樓变汪,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親蚁趁。 傳聞我的和親對(duì)象是個(gè)殘疾皇子裙盾,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,507評(píng)論 2 359