yeojz / otplib

:key: One Time Password (OTP) / 2FA for Node.js and Browser - Supports HOTP, TOTP and Google Authenticator
https://otplib.yeojz.dev
MIT License
1.93k stars 130 forks source link

How to use otplib with Expo? #245

Closed itsabdelrahman closed 4 years ago

itsabdelrahman commented 4 years ago

Describe the bug Getting incorrect TOTPs when using @otplib/core & @otplib/plugin-crypto-js with Expo.

To Reproduce Steps to reproduce the behavior:

  1. Clone this example
  2. yarn
  3. yarn web or yarn ios or yarn android

Expected behavior Getting correct TOTPs in accordance with https://otplib.yeojz.dev or https://rootprojects.org/authenticator using the same secret.

Screenshots Screen Shot 2020-03-08 at 02 01 56

Details

itsabdelrahman commented 4 years ago

@yeojz And thanks a bunch for your time and effort working on this outstanding library! 👏

yeojz commented 4 years ago

hi @ar-maged

Thanks.

Looked at the code. The reason why it is not matching is because you are using totp instead of the authenticator methods. The difference between the two is that the keys used in authenticator are base32 encoded.

i.e. if you want to use totpToken, then you'll have to decode first secret -> base32decode(secret) -> totpToken

Modification:

import { keyDecoder } from '@otplib/plugin-base32-enc-dec';
// assumes the original secret to be already encoded.
 const totp = totpToken(
  keyDecoder(secret, 'hex'),
  totpOptions({
    createDigest,
    encoding: 'hex'
  })
);

image

alternatively, you can use the authenticatorToken method provided by the library.

itsabdelrahman commented 4 years ago

Outstanding! Thank you very much for the thorough explanation 👌