Skip to content
/ jotp Public

๐Ÿ”’ OTP (One Time Password) utility in Java

License

Notifications You must be signed in to change notification settings

amdelamar/jotp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Jotp

Maven Central Javadoc Build Codecov

OTP (One Time Password) utility in Java. To enable two-factor authentication (2FA) using HMAC-based or Time-based algorithms.

Download

Maven:

<dependency>
    <groupId>com.amdelamar</groupId>
    <artifactId>jotp</artifactId>
    <version>1.3.0</version>
</dependency>

Gradle:

dependencies {
    implementation 'com.amdelamar:jotp:1.3.0'
}

SBT:

libraryDependencies ++= Seq(
  "com.amdelamar" % "jotp" % "1.3.0"
)

Or Download the latest release.

Usage

import com.amdelamar.jotp.OTP;
import com.amdelamar.jotp.type.Type;

// Random secret Base32 with 20 bytes (160 bits) length
// (Use this to setup 2FA for new accounts).
String secret = OTP.randomBase32(20);
// Returns: IM4ZL3G5Q66KW4U7PMOQVXQQH3NGOCHQ

// Generate a Time-based OTP from the secret, using Unix-time
// rounded down to the nearest 30 seconds.
String hexTime = OTP.timeInHex(System.currentTimeMillis(), 30);
String code = OTP.create(secret, hexTime, 6, Type.TOTP);

Show the user the QR Code 1

First generate the otpUrl.

// Generate otpauth URL
String otpUrl = OTP.getURL(secret, 6, Type.TOTP, "Example", "[email protected]");
// Returns: "otpauth://totp/Example:[email protected]?secret=IM4ZL3G5Q66KW4U7PMOQVXQQH3NGOCHQ&issuer=Example&algorithm=SHA1&digits=6&period=30";

Then use a service like quickchart.io and paste the otpUrl for the "text" parameter: https://quickchart.io/qr?size=200&text=$otpUrl

QR Image Example

Alternatively, instead of a web service you can use a Java library like nayuki/QR-Code-generator.

After user scans the image with their mobile app we can compare codes.

// Get User's input code for a login...
String userEnteredCode = "123456";

// Verify OTP
if (OTP.verify(secret, userEnteredCode, 6, Type.TOTP)) {
    // Code valid. Login successful.
}

Details

This code currently supports the standard HMAC-based (HOTP RFC 4226) and time-based (TOTP RFC 6238) algorithms for one-time passwords.

It was started as an easy way to enable 2-Factor Authentication for Java based web applications, but it can be applied to other Java applications as well.

Contribute

A project by Austin Delamar based off of Kamron Zafar's work and other contributors.

If you'd like to contribute, feel free to fork and make changes, then open a pull request to master branch.

License

Apache 2.0

1 QR code standard is trademarked by Denso Wave, Inc.