How to use otplib with Expo?
itsabdelrahman opened this issue · comments
Describe the bug
Getting incorrect TOTPs when using @otplib/core
& @otplib/plugin-crypto-js
with Expo.
To Reproduce
Steps to reproduce the behavior:
- Clone this example
yarn
yarn web
oryarn ios
oryarn android
Expected behavior
Getting correct TOTPs in accordance with https://otplib.yeojz.dev or https://rootprojects.org/authenticator using the same secret.
Details
- otplib:
v12.0.1
- node:
v10.15.3
- yarn:
v1.22.1
@yeojz And thanks a bunch for your time and effort working on this outstanding library! 👏
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'
})
);
alternatively, you can use the authenticatorToken method provided by the library.
Outstanding! Thank you very much for the thorough explanation 👌