Project

otp

0.0
No commit activity in last 3 years
No release in over 3 years
An implementation of HOTP (RFC4226) and TOTP (RFC6238).
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Development

~> 1.6
>= 0
 Project Readme

One-Time Password Library

Build Status Gem Version License

This library provides an implementation of HMAC-Based One-Time Password Algorithm (HOTP; RFC4226) and Time-Based One-Time Password Algorithm (HOTP; RFC6238).

Usage

To create new TOTP secret:

require "otp"

# Create a TOTP instance and new key
totp = OTP::TOTP.new
totp.new_secret  # create random secret
p totp.password  #=> "123456" (password for the current time)

# Inspect TOTP parameters
p totp.secret    #=> "YVMR2G7N4OAXGKFC" (BASE32-formated HMAC key)
p totp.algorithm #=> "SHA1" (HMAC algorithm; default SHA1)
p totp.digits    #=> 6 (number of password digits; default 6)
p totp.period    #=> 30 (time step period in second; default 30)
p totp.time      #=> nil (UNIX time by Time or Integer; nil for the current time)

# Format TOTP URI. Otpauth scheme URLs can be read by OTP::URI.parse.
totp.issuer = "My Company"
totp.accountname = "account@exaple.com"
p totp.to_uri    #=> "otpauth://totp/My%20Company:account@exaple.com?secret=47JBA7ZWDDLNZJMX&issuer=My+Company"

To verify given TOTP password:

require "otp"

totp = OTP::TOTP.new
totp.secret = "YVMR2G7N4OAXGKFC"
p totp.verify("123456")  #=> true/false (verify given passowrd)

You can use the last and post option parameters to verify several generations, including before and after the current password.

# verify passwords from last 2 generation to post 1 generation
p totp.verify("123456", last: 2, post: 1)

Related Information

TOTP and HOTP algorithm details can be referred at the following URLs.

In the OTP URI format, the value of "secret" is encoded with BASE32 algorithm. The Format details are described in the document of Google Authenticator.