SwiftOTP is a pure Swift library for generating One Time Passwords (OTP) commonly used for two factor authentication. SwiftOTP supports both HMAC-Based One Time Passwords (HOTP) and Time Based One Time Passwords (TOTP) defined in RFC 4226 and RFC 6238 respectively.
SwiftOTP is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'SwiftOTP'
Then run pod install
in the project directory to install.
let totp = TOTP(secret: data)!
A TOTP Object can be created with the default settings (6 digits, 30sec time interval and using HMAC-SHA-1) as shown above, or the individual parameters can be set as shown below:
let totp = TOTP(secret: data, digits: 6, timeInterval: 30, algorithm: .sha1)!
After creating a TOTP object, a password can be generated for a point in time, either by using a Date
object or a Unix time value using the generate()
function
For example, to get a password for the current time using a TOTP
object named totp
:
totp.generate(time: Date)
Or from Unix time (i.e. seconds elapsed since 00:00 1 Jan 1970):
totp.generate(secondsPast1970: 1234567890)
Note: only Int
values are accepted by this function.
In addition to TOTP, SwiftOTP also supports the generation of counter-based HOTP passwords.
let hotp = HOTP(secret: data)!
A HOTP Object can be created with the default settings (6 digits, using HMAC-SHA-1) as shown above, or the individual parameters can be set as shown below:
let hotp = HOTP(secret: data, digits: 6, algorithm: .sha1)!
After creating a TOTP object, a password can be generated for a counter value by using the generate()
function, for example (where hotp
is a HOTP
object):
hotp.generate(counter: 42)
Most secret keys for generating one time passwords use Base32 encoding. As such, SwiftOTP includes a Base32 Helper to decode a Base32 string into Data
.
For example:
base32DecodeToData("ABCDEFGHIJKLMNOP")!
Or in use:
let data = base32DecodeToData("ABCDEFGHIJKLMNOP")!
let hotp = HOTP(secret: data)!
print(hotp.generate(42)
SwiftOTP supports HMAC with SHA1 as specified in RFC 4226, as well as SHA256 and SHA512 added in RFC 6238. MD5 is not supported due to its inability to produce reliable one time passwords.
Both the TOTP
and HOTP
objects only accept a digit length value between 6 and 8, as specified in RFC 4226. Both objects will return nil
if an invalid digit length value is provided.
SwiftOTP is available under the MIT license. See the LICENSE file for more info.
SwiftOTP depends on the following open-source projects:
- CryptoSwift by Marcin Krzyżanowski (License)
- Base32 by Norio Nomura (License)
Please include the respective licenses in addition to the SwiftOTP license in your project.
Some parts of the password generator code were adapted from the old Google Authenticator source.