java 雙因素認(rèn)證(2FA)demo

很早就知道有這個東西了,一直不知道是怎么實(shí)現(xiàn)的.
比如 QQ 安全中心的密鑰,U盾之類的.
今天看到阮一峰老師的博客才知道實(shí)現(xiàn)原理.
概念性的東西參考
http://www.ruanyifeng.com/blog/2017/11/2fa-tutorial.html
實(shí)現(xiàn)代碼:

package totp;

import java.security.MessageDigest;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TOTP {

    // TC = floor((unixtime(now) ? unixtime(T0)) / TS)
    // TC = floor(unixtime(now) / 30)
    // TOTP = HASH(SecretKey, TC)
    private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();

    public static void main(String[] args) {

        Pattern pattern = Pattern.compile("\\d");
        String key = UUID.randomUUID().toString().replace("-", "");

        for (int i = 0; i < 70; i++) {

            String TC = String.valueOf((int) Math.floor(new Date().getTime() / 1000 / 30));
            String TOTP = sha1(TC + key);

            Matcher matcher = pattern.matcher(TOTP);
            String result = "";
            while (matcher.find()) {
                result += matcher.group();
            }
            result = result.substring(result.length() - 6);
            System.out.println(i + "  --  " + result);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static String sha1(String srcStr) {
        return hash("SHA-1", srcStr);
    }

    public static String hash(String algorithm, String srcStr) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            byte[] bytes = md.digest(srcStr.getBytes("utf-8"));
            return toHex(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String toHex(byte[] bytes) {
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 我們離回憶太近, 離自由太遠(yuǎn)。 有時候念念不忘, 只是愛上回憶。 有一天你會發(fā)現(xiàn), 那些離去的, 不過是你錯愛的人...
    純一新生閱讀 301評論 2 4
  • 我們都不知道,自己最后究竟會成為誰的過客,只是,當(dāng)揮手過后,卻不知道這手,該放在何處,這染了灰的悲涼,豈是三言兩語...
    二姥爺沒有春天閱讀 408評論 0 0
  • 文:茉莉 今天 重要的話 請對我的左耳說 它會仔細(xì)聽 天明 沉寂清醒 右耳鈍然失靈 不止隔層紗 明明 時常抱怨 聽...
    茉莉的小茶館閱讀 322評論 2 3

友情鏈接更多精彩內(nèi)容