个人比较推荐使用BastiaanJansen/otp-java,使用简单,而且包含了生成以及校验
参考代码
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>lakefs-app</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.github.bastiaanjansen</groupId>
<artifactId>otp-java</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
</dependencies>
</project>
代码
package com.dalong;
import com.bastiaanjansen.otp.HMACAlgorithm;
import com.bastiaanjansen.otp.TOTP;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
public class App {
static final String myKey = "dddddd";
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
TOTP.Builder builder = new TOTP.Builder(myKey.getBytes());
builder
.withPasswordLength(6)
.withAlgorithm(HMACAlgorithm.SHA1) // SHA256 and SHA512 are also supported
.withPeriod(Duration.ofSeconds(30));
TOTP totp = builder.build();
String mycode = totp.now();
System.out.println(mycode);
}
}
说明
otp 做为系统双因素认证是一个简单方便的东西,我们可以方便的基于开源的otp包开发自己的otp集成方案
可能在使用中会有Caused by: java.lang.ClassNotFoundException: org.apache.commons.codec.binary.Base32 的问题
以为bastiaanjansen的otp 依赖了commons.codec,因为项目依赖冲突了,解决方法很简单,就是添加依赖(参考上边的)
参考资料
https://github.com/BastiaanJansen/otp-java
https://github.com/jchambers/java-otp
https://github.com/amdelamar/jotp