0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ワンタイムパスワードを CLI から生成し,クリップボードに貼り付ける

Posted at

はじめに

大学のシステムにログインする際や,GitHub にログインする際に,ワンタイムパスワードが求められますよね.
これまでは,以下の手順でログインしていました.

  1. ユーザ名,パスワードの入力
  2. ワンタイムパスワードを取得するためにスマホを開く
  3. スマホの画面を見ながら,ワンタイムパスワードの入力

いちいちスマホを開くのが面倒 !

ワンタイムパスワードを見るためだけに,スマホのロックを解除し,Google Authenticator を起動するのがめんどうだと感じていました.
そのため,ターミナルからコマンド1つでワンタイムパスワードを生成し,クリップボードに貼り付けられるようにすればいいのではないかと考えました.

環境

PC: M4 MacBook Pro
OS: macOS Sequoia 15.0

作成したプログラム

<your secret key> のなかは,自身で取得した秘密鍵を入れてください.

#!/bin/bash

SECRET="<your secret key>"

OTP=$(python3 - <<EOF
import base64
import hmac
import hashlib
import struct
import time

def generate_totp(secret):
    key = base64.b32decode(secret, casefold=True)
    timestep = int(time.time()) // 30
    msg = struct.pack(">Q", timestep)
    hmac_hash = hmac.new(key, msg, hashlib.sha1).digest()
    offset = hmac_hash[-1] & 0x0F
    binary = struct.unpack(">I", hmac_hash[offset:offset + 4])[0] & 0x7FFFFFFF
    return '{:06d}'.format(binary % 1000000)

print(generate_totp("$SECRET"))
EOF
)

echo -n "$OTP" | pbcopy
echo "Token: $OTP "

使用例

ここでは,作成したプログラムを google_auth というファイル名で保存することにします.

  1. お好きなディレクトリでエディタを開き,google_auth にプログラムをコピペします

  2. 秘密鍵を取得し,コピペします.

    注意
    秘密鍵を直接ソースコード内に含めたくない場合は,.env に逃すなど適宜行ってください

  3. google_auth に実行権限を付与する.

    $ chmod +x google_auth
    
  4. パスが通っている場所にシンボリックリンクをはる.
    プログラムを直接/bin/などに置きたくなかったため,シンボリックリンクをはることにしました.

    1. パスが通っている場所 (例: .local/bin/) に移動する.
      $ cd ~/.local/bin
      
    2. シンボリックリンクをはる.
      $ ln -s path/to/google_auth google_auth
      
  5. google_auth を実行する.

    $ google_auth
    
  6. ワンタイムパスワードが出力され,クリップボードに保存されていることを確認する.

    $ Token: 000000
    

まとめ

今回は,ワンタイムパスワードを CLI から生成し,クリップボードに貼り付ける方法について紹介しました.
少しでもお役にたてれば幸いです.

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?