Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9038

TOTPの任意の時間のコードをNode.jsで出力する

$
0
0
2段階認証でxx AuthenticatorのようなアプリでTOTP(Time-Based One-Time Password)を表示しているが、 残り時間が少なく入力が間に合わない場合、次のパスワードが出るまで待つ必要がある。 次のパスワードも出してくれたらいいのに…と思い、Node.jsで出すようにしてみたときのメモ QRコード生成 Authenticatorアプリで同じパスワードが出ているか確認したいが、本当に使っているアカウントで試すのも躊躇われるので、アプリに登録するためのQRコードを作成する。 QRコードの内容は下記。パスワード生成に必要なSecretはTESTAPPSECRETAAAとする。 otpauth://totp/testapp:testuser@example.com?secret=TESTAPPSECRETAAA&issuer=testapp `otpauth:...のURIについてはGoogle AuthenticatorのKey-Uri-Formatを参照。 このURIからqrcode-terminalやqrcode等を利用してQRコードを生成する。 ワンタイムパスワード生成 npmパッケージのotplibを利用する。 otpSample.js const { authenticator } = require('otplib'); const SECRET = 'TESTAPPSECRETAAA'; console.log(authenticator.generate(SECRET)); console.log(`残り時間: ${authenticator.timeRemaining()}`); authenticator.options = {epoch: Date.now() + (30 * 1000)}; console.log(`次のコード: ${authenticator.generate(SECRET)}`); otplibはTOTP、HOTPのワンタイムパスワードを扱うライブラリーであるが、otplib.authenticator.generate(${Secret Key})で某Authenticator互換の設定がプリセットされた状態でパスワードが生成できる。 デフォルトでは現在時刻をベースにパスワードを生成するが、オプション(authenticator.options)のepochで任意の時刻を指定すればその時刻がベースになる。 パスワードの有効期間は30秒なので、現在時刻+30秒後の時刻を入れれば次のパスワードを取得できる。 残り時間がauthenticator.timeRemaining()で取得できるので一応表示する。 出力例 $ node otpSample.js 675136 残り時間: 5 次のコード: 793242 ※ 文中の社名、商品名等は各社の商標または登録商標である場合があります。 ※ Google and Google Authenticator are trademarks of Google LLC and this document is not endorsed by or affiliated with Google in any way. ※ QRコードは株式会社デンソーウェーブの登録商標です。

Viewing all articles
Browse latest Browse all 9038

Trending Articles