1. 程式人生 > 其它 >幾個不錯的java otp 包

幾個不錯的java otp 包

個人比較推薦使用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