java 雙因素認證(2FA)TOTP demo


TOTP 的全稱是"基於時間的一次性密碼"(Time-based One-time Password)。它是公認的可靠解決方案,已經寫入國際標准 RFC6238。
很早就知道有這個東西了,一直不知道是怎么實現的.
比如 QQ 安全中心的密鑰,U盾,就是動態密碼之類的.
今天看到阮一峰老師的博客才知道實現原理.
概念性的東西參考
http://www.ruanyifeng.com/blog/2017/11/2fa-tutorial.html
實現代碼:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM