A C# library for generating and validating one time passwords (TOTP only) according to RFC 6238.
RsctOtp is compatible with Google Authenticator available for Android and iPhone and any other TOTP based implementations.
- .NETStandard 2.0
Build and install the DLL into your project.
- Publish the DLL (e.g. with VisualStudio)
- Import the DLL (RsctOtp.dll) into your project
Totp totp = new TOTP("base32secret3232", issuer: "My Service")
totp.Now # => "492039"
# OTP verified for current time - returns timestamp of the current interval
# period.
totp.Verify("492039") # => 1474590700
# OTP fails to verify - returns nil
totp.Verify("492039") # => nil
By keeping track of the last time a user's OTP was verified, we can prevent token reuse during the interval window (default 30 seconds)
The following is an example of this in action:
User user = User.find(someUserID)
Totp totp = new TOTP(user.otp_secret)
totp.Now # => "492039"
# Let's take a look at the last time the user authenticated with an OTP
user.last_otp_at # => 1432703530
# Verify the OTP
DateTime after = DateTimeOffset.FromUnixTimeSeconds(user.last_otp_at).UtcDateTime
last_otp_at = totp.Verify("492039", after: after) #=> 1472145760
# RSCT_OTP returns the timestamp(int) of the current period
# Store this on the user's account
user.update(last_otp_at: last_otp_at)
# Someone attempts to reuse the OTP inside the 30s window
after = DateTimeOffset.FromUnixTimeSeconds(user.last_otp_at).UtcDateTime
last_otp_at = totp.Verify("492039", after: after) #=> null
# It fails to verify because we are still in the same 30s interval window
Some users may enter a code just after it has expired. By adding 'drift' you can allow for a recently expired token to remain valid.
Totp totp = new TOTP("base32secret3232")
DateTime now = DateTimeOffset.FromUnixTimeSeconds(1474590600).UtcDateTime #2016-09-23 00:30:00 UTC
totp.At(now) # => "250939"
# OTP verified for current time along with 15 seconds earlier
# ie. User enters a code just after it expired
totp.Verify("250939", driftBehind: 15, at: now.AddSeconds(35)) # => 1474590600
# User waits too long. Fails to validate previous OTP
totp.Verify("250939", driftBehind: 15, at: now.AddSeconds(45)) # => null
Base32.random() # returns a 160 bit (32 character) base32 secret. Compatible with Google Authenticator
Note: The Base32 format conforms to RFC 4648 Base32
Provisioning URI's generated by RSCT_OTP are compatible with most One Time Password applications, including Google Authenticator.
Totp totp = new TOTP("base32secret3232", issuer: "My Service")
totp.provisioningUri("[email protected]") # => 'otpauth://totp/My%20Service:[email protected]?secret=base32secret3232&issuer=My%20Service'
This can then be rendered as a QR Code (not included in this library) which the user can scan using their mobile phone and the appropriate application.
A testing project is included as "RsctOtp.Test"
This software is released under MIT licence. See LICENSE file.