2段階認証のワンタイムパスコードを生成するQRコードを自作したかったので、Node.jsスクリプトを作成した。
QRコード仕様
Google AuthenticatorのKey-Uri-Formatによると、QRコードの内容は下記とのこと
otpauth://${TYPE}/${LABEL}?${PARAMETERS}
TYPE: hotp(HMAC-Based One-Time Password Algorithm)かtotp(Time-Based One-Time Password Algorithm)。某Authenticatorはtotp
LABEL: ${発行者}:${アカウント名}または${アカウント名}で記入。発行者が記入されているほうを推奨するとのこと
PARAMETERS: secret=${SECRET}&issuer=${発行者}のように記入
secret: 必須。Base32文字列を記入。16文字が多い。アカウント毎に異なるものを指定する
issuer: 強く推奨。LABELに記入した発行者と同じものを記入
algorithm: optional。アルゴリズム。デフォルトはSHA1
digits: optional。パスコードの長さ。6か8を指定可で、デフォルトは6
counter: TYPEがhotpであれば必須。HOTP用カウンター
period: optional。TOTPでパスコードが有効な秒数を指定。デフォルトは30
PARAMETERSのoptionalで指定できるパラメーターはアプリによっては無視される様子。
QRコード出力
npmパッケージのqrcode-terminalを利用してスクリプトを作成した。QRコードがCLIで出力される。
otpQRGenerator.js
const qrcode = require('qrcode-terminal');
const TYPE = 'totp';
const ISSUER = 'testapp';
const ACCOUNT_NAME = 'testuser@example.com';
const SECRET = 'TESTAPPSECRETAAA';
// SECRETを生成する場合、otplib(https://www.npmjs.com/package/otplib)で生成できる
// const { authenticator } = require('otplib');
// const SECRET = authenticator.generateSecret();
const url = `otpauth://${TYPE}/${ISSUER}:${ACCOUNT_NAME}?secret=${SECRET}&issuer=${ISSUER}`;
qrcode.generate(url, {small: true}, (qrcodeImage) => {
console.log(qrcodeImage);
process.exit(0);
});
実行例
$ node otpQRGenerator.js
▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
█ ▄▄▄▄▄ █▄▀ ▀ ▄▄▀ ▄▄ █ ▄███▄█ ▄▄▄▄▄ █
█ █ █ █ █▀█▀▀▄▀▄█▄▀▀█▄ ▀▄█ █ █ █
█ █▄▄▄█ █▄█▀ ▄▀▄▀ ▄ █▄█ ██ █ █▄▄▄█ █
█▄▄▄▄▄▄▄█▄█ █ █▄▀ ▀ █ █▄▀ █ ▀▄█▄▄▄▄▄▄▄█
█ ▄ ▄▀▀▄█▄▀ ▄ ▀ █▄▄▄▀▀█▀██▄█▀ █▀▄▄▄▀▄█
(中略)
███████▄█▀█▄▄▀▀█▀██ ▀▀█▄▀▄▄▄▀ ▄▄▄ █ █
█ ▄▄▄▄▄ ██▄ ▄ ██▄▀▀█▀ ▄█▀▀▄ ▀ █▄█ █ █
█ █ █ █▀█▄▄ ▀█▀▄ ▄▀▀▀ ██▄█▄ █▀▀▀█
█ █▄▄▄█ █ ▀▄▄▄▄█▀ ▄ ▀▀▄█ ▄█▀▄ ▄ ███
█▄▄▄▄▄▄▄█▄▄██▄█▄▄▄▄███▄▄▄▄▄▄███▄▄██▄▄▄█
これをAuthenticatorのアプリで読み込むと
testapp(testuser@example.com)で登録される。
QRコードはqrcode.generateのオプションに{small: true}を追加するとアスキーアートで表示されるが、フォントによってはうまく読み込めない。その場合はオプションを外すか、qrcode等で画像ファイルで出力したほうがよい。
※ 文中の社名、商品名等は各社の商標または登録商標である場合があります。
※ Google and Google Authenticator are trademarks of Google LLC and this document is not endorsed by or affiliated with Google in any way.
※ QRコードは株式会社デンソーウェーブの登録商標です。
↧