Giter Site home page Giter Site logo

mattrubin / onetimepassword Goto Github PK

View Code? Open in Web Editor NEW
333.0 13.0 102.0 1.19 MB

๐Ÿ”‘ A small library for generating TOTP and HOTP one-time passwords on iOS.

License: MIT License

Swift 100.00%
swift totp hotp two-factor-authentication one-time-passwords 2fa ios otp

onetimepassword's Introduction

OneTimePassword

TOTP and HOTP one-time passwords for iOS

Xcode CI status SPM CI status Carthage CI status Code Coverage Swift 5.x Platforms: iOS, macOS, watchOS MIT License

The OneTimePassword library is the core of Authenticator. It can generate both time-based and counter-based one-time passwords as standardized in RFC 4226 and RFC 6238. It can also read and generate the "otpauth://" URLs commonly used to set up OTP tokens, and can save and load tokens to and from the iOS secure keychain.

Installation

Add the following line to your Cartfile:

github "mattrubin/OneTimePassword" ~> 4.0

Then run carthage update OneTimePassword to install the latest version of the framework.

Be sure to check the Carthage README file for the latest instructions on adding frameworks to an application.

Add the following line to the dependencies section of your package manifest:

.package(url: "https://github.com/mattrubin/OneTimePassword.git", from: "4.0.0"),

Then add "OneTimePassword" to the dependencies array of any target which should be linked with this library.

Usage

The latest version of OneTimePassword compiles with Swift 5. To use OneTimePassword with earlier versions of Swift, check out the swift-4.2, swift-4, swift-3, and swift-2.3 branches. To use OneTimePassword in an Objective-C based project, check out the objc branch and the 1.x releases.

Create a Token

The Generator struct contains the parameters necessary to generate a one-time password. The Token struct associates a generator with a name and an issuer string.

To initialize a token with an otpauth:// url:

if let token = Token(url: url) {
    print("Password: \(token.currentPassword)")
} else {
    print("Invalid token URL")
}

To create a generator and a token from user input:

This example assumes the user provides the secret as a Base32-encoded string. To use the decoding function seen below, add import Base32 to the top of your Swift file.

let name = "..."
let issuer = "..."
let secretString = "..."

guard let secretData = MF_Base32Codec.data(fromBase32String: secretString),
    !secretData.isEmpty else {
        print("Invalid secret")
        return nil
}

guard let generator = Generator(
    factor: .timer(period: 30),
    secret: secretData,
    algorithm: .sha1,
    digits: 6) else {
        print("Invalid generator parameters")
        return nil
}

let token = Token(name: name, issuer: issuer, generator: generator)
return token

Generate a One-Time Password

To generate the current password:

let password = token.currentPassword

To generate the password at a specific point in time:

let time = Date(timeIntervalSince1970: ...)
do {
    let passwordAtTime = try token.generator.password(at: time)
    print("Password at time: \(passwordAtTime)")
} catch {
    print("Cannot generate password for invalid time \(time)")
}

Persistence

Token persistence is managed by the Keychain class, which represents the iOS system keychain.

let keychain = Keychain.sharedInstance

The PersistentToken struct represents a Token that has been saved to the keychain, and associates a token with a keychain-provided data identifier.

To save a token to the keychain:

do {
    let persistentToken = try keychain.add(token)
    print("Saved to keychain with identifier: \(persistentToken.identifier)")
} catch {
    print("Keychain error: \(error)")
}

To retrieve a token from the keychain:

do {
    if let persistentToken = try keychain.persistentToken(withIdentifier: identifier) {
        print("Retrieved token: \(persistentToken.token)")
    }
    // Or...
    let persistentTokens = try keychain.allPersistentTokens()
    print("All tokens: \(persistentTokens.map({ $0.token }))")
} catch {
    print("Keychain error: \(error)")
}

To update a saved token in the keychain:

do {
    let updatedPersistentToken = try keychain.update(persistentToken, with: token)
    print("Updated token: \(updatedPersistentToken)")
} catch {
    print("Keychain error: \(error)")
}

To delete a token from the keychain:

do {
    try keychain.delete(persistentToken)
    print("Deleted token.")
} catch {
    print("Keychain error: \(error)")
}

License

OneTimePassword was created by Matt Rubin and the OneTimePassword authors and is released under the MIT License.

onetimepassword's People

Contributors

algesten avatar bas-d avatar ericlewis avatar mattrubin avatar mike-engel avatar trsathya avatar ziogaschr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

onetimepassword's Issues

Swift 3 Update

Hi, can you update the code for swift 3. It would be great of you to help me out

Privacy Manifest

Is this repository subject to any of the privacy manifest requirements? Wanted to check if this can be added if so.

Sharing Keychain

I've been tweaking the code to be able to share the keychain

So far I was unable to do so.
So what have I done...
On the entitlements I added the keychain group

SEED.bundle (this is a fake value just so you can have an idea, the app has the real code)

After having Key Sharing enabled for all apps with the group mentioned above I started tweaking with the Keychain.swift file

In the function
private func addKeychainItem(withAttributes attributes: [String: AnyObject]) throws -> Data {
added this line
mutableAttributes[kSecAttrSynchronizable as String] = kCFBooleanTrue

And other two functions

private func keychainItem(forPersistentRef persistentRef: Data) throws -> NSDictionary? {
private func allKeychainItems() throws -> [NSDictionary] {

Added the line
kSecAttrSynchronizable as String: kCFBooleanTrue,

After all this the app was still working but the sync isn't, I figured out that I'm missing to witch group will the functions will access

so I created a constant
private let kSAAGroup = "SEED.bundle"

And on this function
func keychainAttributes() throws -> [String: AnyObject] {
I tried to add this line
kSecAttrAccessGroup as String: kSAAGroup as NSString,

From here the app stopped working properly giving me the error when trying to save a new token

Keychain error: systemError(-34018)

From here I don't know what to do.

BTW: I'm not enrolled in the Apple Dev Program, I'm using the my Apple ID to sign the app
I'm running the app in a Device and not on a Simulator

Any help on this area?

Build failed with carthage

Hi,
I was trying to build the api with carthage but give the below output.

usr/bin/xcrun xcodebuild -workspace /Users/admin/Documents/sample\ code/TestAPIClient/Carthage/Checkouts/OneTimePassword/OneTimePassword.xcworkspace -scheme OneTimePassword\ (iOS) -configuration Release -derivedDataPath /Users/admin/Library/Caches/org.carthage.CarthageKit/DerivedData/9.2_9C40b/OneTimePassword/3.0 -sdk iphoneos ONLY_ACTIVE_ARCH=NO BITCODE_GENERATION_MODE=bitcode CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES archive -archivePath /var/folders/x7/wzg7gmy96hq5jfr63rg30t380000gp/T/OneTimePassword SKIP_INSTALL=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=NO CLANG_ENABLE_CODE_COVERAGE=NO (launched in /Users/admin/Documents/sample code/TestAPIClient/Carthage/Checkouts/OneTimePassword)

This usually indicates that project itself failed to compile. Please check the xcodebuild log for more details: 

I tried builiding the project itself but gives me CryptoKit missing error.
How to fix this ?

Error on build

HI guys,

i have an error when I'm try build OneTimePassword by POD:

.../Pods/OneTimePassword/CommonCrypto/iphonesimulator/module.modulemap:1:8: error: redefinition of module 'CommonCryptoShim'
module CommonCryptoShim [system] {
       ^
.../ExpressAccessKit/Carthage/Checkouts/OneTimePassword/CommonCrypto/iphonesimulator/module.modulemap:1:8: note: previously defined here
module CommonCryptoShim [system] {
       ^
<unknown>:0: error: could not build Objective-C module 'CommonCrypto'

I am using Xcode : Version 10.2 (10E125)
CocoaPods : 1.6.1

Support watchOS through Carthage

Hey it would be awesome if you could get a version of this framework working with watchOS. I want to include it in my project and will be using it on the watch

From a little research I believe the only thing that needs to be done is to add a target in the Base32 library that targets watchOS

Support for this would be awesome and thanks in advance

Cannot generate accepted password on swift-3-api-style

Hello there,

Currently using Swift 3 and as a result the swift-3-api-style branch. However, I am not able to have a Generator generate valid passwords. Each time I go to use them in multiple different providers (have tried gandi.net, github, Google), the one-time passwords I enter are not accepted.

I am unsure of what I am doing incorrectly. I'm instantiating the Generator as such:

open override var generator: Generator {
        return Generator(
            factor: Generator.Factor.timer(period: interval),
            secret: secret.data(using: String.Encoding.utf8)!,
            algorithm: algorithm,
            digits: tokenLength
        )!
    }

One thing I am not clear about is how the encoding should work. The README says to use NSData(base32String: ...) but I notice that on the new branch, String.data(using: String.Encoding.ascii) is used in the tests.

Please advise. Thanks and appreciate your help.

OneTimePassword as a pod dependency

When I add OneTimePassword as a pod (checked out form my git fork, which has added *swift files as a source) I got following error:

~/OneTImePasswordPodTest/Pods/OneTimePassword/OneTimePassword/OneTimePassword-Bridging-Header.h:9:9: error: include of non-modular header inside framework module 'OneTimePassword.OneTimePassword_Bridging_Header'
#import <CommonCrypto/CommonHMAC.h>
        ^
<unknown>:0: error: could not build Objective-C module 'OneTimePassword'

I'm using CocoaPods 0.36.1

How to overcome this?

How to generate a 5 digit TOTP ?

I've tried the following logic, but it fails when I try to create 5 digit OTP.

`let secret = "fvfsdvfsvdfbedfgvdfbgvdbvgfbdvbgvtgnbvcxbgIvnlsn"
// base 32
guard let secretData = MF_Base32Codec.data(fromBase32String: secret),
!secretData.isEmpty else {
print("Invalid secret")
return
}

    if let totp = Generator(factor: .timer(period: 30), secret: secretData, algorithm: .sha1, digits: 5)
         {
        
            let pasword = try! totp.password(at: Date())
            print(pasword)
            
    } else {
        print("Failed to Generate.")
    }`

CocoaPod-swift3-version and Carthage-swift3-version both not running out-of-the-box

Hi there,

Great that you have rewritten OneTimePassword to work on Swift 3. Unfortunately we discovered some problems with the implementation of this library. Both for the CocoaPod as the Carthage version I got different errors.

First: the CocoaPod version.
When using the CocoaPod version, adjustments have to be made on the example-code of the generator in order to get the code running:

Statement in Podfile:
pod 'OneTimePassword', '~> 3.0'

The example code:

let name = "..."
let issuer = "..."
let secretString = "..."

guard let secretData = Data(base32String: secretString),
    !secretData.isEmpty else {
        print("Invalid secret")
        return nil
}

When trying to run this, the following error will be provided:
Argument labels '(base32String:)' do not match any available overloads

The adjusted code in order to get it running with the CocoaPod version:

let name = "..."
let issuer = "..."
let secretString = "..."

guard let secretData = NSData(base32String: secretString),
    secretData.length > 0 else {
        print("Invalid secret")
        return ""
}

Additionally, also one adjustment had to be made in the BridgingHeader:

#import "Base32/MF_Base32Additions.h"

Most likely, it now works like a charm.

Second: the Carthage version.

Statement in Cartfile
github "mattrubin/OneTimePassword" ~> 3.0

When using the Carthage version, the code does run out of the box as described in the example except for that the module "OneTimePassword" is missing the module CommonCrypto. We discovered that this problem occurs when trying to run the code on a simulator. There are workarounds like here . Running it on a device should be no problem, the problem is running it on a simulator.

Could you perhaps take a look at this? I still think OneTimePassword is a great library.

Redefinition of module 'CommonCrypto'

I make a framework named my_framework.framework ,my_framework.framework called the onetimepassword, all seems is ok, but when a app call my_framework.framework ,it hint: missing CommonCrypto, then i add CommonCrypto to my app ,and go to Build Settings, Swift Compiler โ€“ Search Paths and set Import Paths to point to the directory that contains the CommonCrypto directory. then i get the error:

..../Pods/OneTimePassword/CommonCrypto/iphonesimulator/module.modulemap:1:8: Redefinition of module 'CommonCrypto'

Use of unresolved identifier 'HMAC'

Hi there,

I installed your lib using CocoaPods; It's reporting an issue with resolving the HMAC function.

pod 'OneTimePassword', '~> 3.0'

image

Is this a known issue?

Thanks.

Unable to create token from input data

While implementing this library I was unable to add the codes manually.
It fails at this step

guard let secretData = Data(base32String: secretString), //error in this line
    !secretData.isEmpty else {
        print("Invalid secret")
        return nil
}

In Swift3 I get the error on the marked line saying

Argument labels '(base32String:)' do not match any available overloads

I took a look into the code on Base32 and OneTimePassword libraries, but was unable to figure out the solution

How can I calculate the Time Remaining on the current code?

I'm displaying a count down for the current token to the user, much like Google authenticator or Authy.
Except I need to know how much time is remaining on that token, so that I can set the UI to be correct & update the UI at the right time.

Is there an easy calculation for this? or could this be added to the framework? I think it would be quite vital for the implementation

defaultIssuer and defaultName are internal and cannot be referenced

I get the following errors when building my application:

In Token.swift:
Static let 'defaultIssuer' is internal and cannot be referenced from a default argument value
Static let 'defaultName' is internal and cannot be referenced from a default argument value

I have added OneTimePassword with cocoapods and my application uses Swift4.

Why is it requesting Biometric Id verification?

Hi,

First of all thanks for this great lib, it's awesome.

I'm using this but I noticed that when I do call allPersistentTokens() my app requests face id verification, otherwise, it won't let me read the values stored in the keychain, is there a way I can avoid that and get the items? I was trying to identify in the code where you set that but I can't not find it, do you know what's going on and how can I disable that? is it on token creation ?

Any guide is very much appreciated, thanks

Keychain accessibility

Thanks for your work on this library and the associated app!

As far as I could see, you do not specify a value for the kSecAttrAccessible attribute, which specifies the policy for the keychain items used to store the passwords. Therefore it isn't really clear what happens. The result is probably kSecAttrAccessibleWhenUnlocked, which means the values are accessible when the device is unlocked and are backed up when using an iTunes encrypted backup, which is the behavior I want. But I would like to be sure.

Unfortunately I don't have spare iOS devices to test.

Could you please add an explicit value for this attribute so it is clear what happens and so it doesn't change if Apple decides to change the default?

Swift 5 compatibility

OneTimePassword is the last of the dependencies we use at my company to show up in the "Migrate to Swift 5" list in Xcode. The necessary changes to add Swift 5 conformance boil down to two small #if swift(>= 5.0) sections and the declaration of version compatibiliy in the .podspec via the new s.swift_versions property that just became available in CocoaPods 1.7.0.

Before posting this PR, I wanted to make sure if this the right approach?
snabble@cb145c0

secret is missing in toURL() function

I would like to generate QR based on token URL, but the secret param is missing.

Am I doing something wrong? or does some reason exist for not including param?

Thank you.

Generating wrong code

Hi very new to this library but I have an issue.

I take an otpauth:// url, and generate a token from it, except it is generating the wrong password.

I am getting it from this website:
https://daplie.github.io/browser-authenticator/

let url = URL(string: metadataObj.stringValue)
				
if let token = Token(url: url!) {
	print("Password: \(token.currentPassword!)") //This prints the wrong code
	print("Name: \(token.issuer)")					
}

Any ideas?

Add CocoaPods subspec for library without Keychain library

Hello @mattrubin and thanks for building this awesome library.

We want to use your lib in a project with some different needs for the Keychain storage implementation.

I have already implemented the lib with our own library for Keychain persistance and works great, although I had to manually add the files into my project in order I skip the Keychain.swift.

Would you accept a PR that adds a new subspec for CocoaPods without Keychain lib?
You can check what I mean here

Support macOS with a new release with updated podspec and SPM support

The podspec in the latest release 3.2.0 has platform restrictions but I see the develop branch's podspec doesn't. Also the develop branch has a Package.swift to support SPM but the latest release doesn't. When would the next release be to update the podspec in the cocoapods repo and support SPM?

Different TOTP result than Google Authenticator app

Hello @mattrubin and thanks for the great work you have done.

I have setup a site in Google Authenticator app and I am trying to get the same TOTP in an app using your library, although probably I am doing something wrong and I get a different one which doesn't work on the site I have setup 2FA.

The code I am using looks like:

  if let secret = "SOMECHARS".dataUsingEncoding(NSASCIIStringEncoding) {
    if let totp = Generator(factor: .Timer(period: 30), secret: secret, algorithm: .SHA1) {
      println("SHA1", totp.password!)
    }
  }

Can you please help me?

p.s: I am testing the code in the same physical device where Google Authenticator is installed, so the time is the same one.

I a getting this error on adding the pod

module CommonCrypto [system] {
header "/Library/Developer/CommandLineTools/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/CommonCrypto/CommonCrypto.h"
export *
}

error: 'deallocate(capacity:)' is deprecated

I'm using Xcode version 9.3 (9E145) to build from Carthage.

Checkouts/OneTimePassword/Sources/Crypto.swift:33:20: error: 'deallocate(capacity:)' is deprecated: Swift currently only supports freeing entire heap blocks, use deallocate() instead
    defer { macOut.deallocate(capacity: hashLength) }
                   ^

** ARCHIVE FAILED **


The following build commands failed:
        CompileSwiftSources normal arm64 com.apple.xcode.tools.swift.compiler
        CompileSwift normal arm64
(2 failures)

How can we contact you ?

Hi Matt,

We are trying to contact you. I've sent you a few emails, but I am not sure if you've received them. In any case, please let me know how I can contact you.

Thanks.

OSX Target

I'm using OneTimePassword for an OSX project. I had to manually change the project to add an OSX target. Is there any desire to add the target to the official release?

Incorrect results for SHA256 and SHA512

Based on RFC 6238 Appendix B, this library appears to yield incorrect results when using .SHA256 or .SHA512 as the algorithm for a Generator.

class TokenTests: XCTestCase {
    let secretData = "12345678901234567890".dataUsingEncoding(NSASCIIStringEncoding)!

    // ...

    // https://tools.ietf.org/html/rfc6238#appendix-B
    func testAppendixB() {
        guard let
            sha1Generator   = rfcGenerator(.SHA1),
            sha256Generator = rfcGenerator(.SHA256),
            sha512Generator = rfcGenerator(.SHA512)
        else {
            return XCTFail()
        }
        let times: [NSTimeInterval] =
            [59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000]
        let passwords = [
            ["94287082", "07081804", "14050471", "89005924", "69279037", "65353130"],
            ["46119246", "68084774", "67062674", "91819424", "90698825", "77737706"],
            ["90693936", "25091201", "99943326", "93441116", "38618901", "47863826"]
        ]

        let sha1Token   = Token(generator: sha1Generator)
        let sha256Token = Token(generator: sha256Generator)
        let sha512Token = Token(generator: sha512Generator)

        for i in 0..<times.count {
            XCTAssertEqual(passwords[0][i], try? sha1Token.generator.passwordAtTime(times[i]))
            XCTAssertEqual(passwords[1][i], try? sha256Token.generator.passwordAtTime(times[i]))
            XCTAssertEqual(passwords[2][i], try? sha512Token.generator.passwordAtTime(times[i]))
        }
    }

    func rfcGenerator(algorithm: Generator.Algorithm) -> Generator? {
        return Generator(
            factor:    .Timer(period: 30),
            secret:    secretData,
            algorithm: algorithm,
            digits:    8
        )
    }
}
("Optional("46119246")") is not equal to ("Optional("32247374")")

("Optional("90693936")") is not equal to ("Optional("69342147")")

("Optional("68084774")") is not equal to ("Optional("34756375")")

("Optional("25091201")") is not equal to ("Optional("63049338")")

("Optional("67062674")") is not equal to ("Optional("74584430")")

("Optional("99943326")") is not equal to ("Optional("54380122")")

("Optional("91819424")") is not equal to ("Optional("42829826")") - 

("Optional("93441116")") is not equal to ("Optional("76671578")") - 

("Optional("90698825")") is not equal to ("Optional("78428693")") - 

("Optional("38618901")") is not equal to ("Optional("56464532")") - 

("Optional("77737706")") is not equal to ("Optional("24142410")") - 

("Optional("47863826")") is not equal to ("Optional("69481994")") - 

Am I missing something?

Linux support

Would you be interested in a PR that adds support for Linux? Things that would need to change would be references to CommonCrypto and the Keychain. I'd be happy to do such work, just want to check it's something you might be interested in reviewing.

Build cache is always invalid

For some reason, the build cache of this project is always considered invalid by Carthage ๐Ÿค”

This results in this project always having to be built again when running carthage update --cache-builds:

*** Invalid cache found for OneTimePassword, rebuilding with all downstream dependencies

It seems to work for all other of my dependencies so I'm guessing that there is something special going on here ๐Ÿค”

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.