HOTP的工作原理
HTOP(K,C) = Truncate(HMAC-SHA-1(K,C))
客户端和服务器事先协商好一个密钥K,用于一次性密码的生成过程。此外,客户端和服务器各有一个计数器C,并且事先将计数值同步。而Truncate是为了获得一个符合HTOP要求的值。
TOTP的工作原理
Time-based One-time Password (TOTP):即基于时间的一次性密码算法,也称时间同步的动态密码。
TOTP = Truncate(HMAC-SHA-1(K,T))
TOTP是HOTP的一个变种,将HOTP中的计数器C替换为依托时间的参数T,T是由当前时间(CurrentUnixTime、初始时间(T0)、步长(X)决定的。
即:T = (Current Unix time – T0) / X
- CurrentUnixTime:当前的Unix时间。
- T0: 开始计步初始化时间,默认为0
- X : 步长,默认情况下为30s
TOTP的一些要求
- 客户端和服务器必须能够彼此知道或者推算出对方的Unix Time
- 客户端和服务器端必须共享一个密钥
- 算法必须使用HOTP作为其关键实现环节
- 客户端和服务器端必须使用相同的步长X
- 每一个客户端必须拥有不同的密钥
- 密钥的生成必须足够随机
- 密钥必须储存在防篡改的设备上,而且不能在不安全的情况下被访问或使用。
- 对该算法中T的实现必须大于int32,因为它在2038年将超出上限。
- T0和X的协商必须在之前的步骤中就已经做好了。
原理摘抄于 https://www.sooele.com/1529.html
<dependency>
<groupId>com.eatthepath</groupId>
<artifactId>java-otp</artifactId>
<version>0.2.0</version>
</dependency>
@Test
void testHotp() throws DecoderException, InvalidKeyException, NoSuchAlgorithmException {
HmacOneTimePasswordGenerator hmacOneTimePasswordGenerator = new HmacOneTimePasswordGenerator(8);
String key = "123456";
byte[] binaryKey = Hex.decodeHex(key.toCharArray());
SecretKeySpec secretKeySpec = new SecretKeySpec(binaryKey, "HmacSHA1");
System.out.println(hmacOneTimePasswordGenerator.generateOneTimePassword(secretKeySpec,12345678));
}
@Test
void testTotp() throws DecoderException, InvalidKeyException, NoSuchAlgorithmException {
TimeBasedOneTimePasswordGenerator totpGenertor = new TimeBasedOneTimePasswordGenerator(Duration.ofMinutes(1L));
final Instant now = Instant.now();
String key = "123456";
byte[] binaryKey = Hex.decodeHex(key.toCharArray());
SecretKeySpec secretKeySpec = new SecretKeySpec(binaryKey, "HmacSHA1");
System.out.println(totpGenertor.generateOneTimePassword(secretKeySpec,now));
}