Wizard Notes

Python, JavaScript を使った音楽信号分析の技術録、作曲活動に関する雑記

Pythonでのパスワード用ランダム文字列の作成メモ

Python インタプリタを起動してパスワード用のランダムな文字列をさくっと生成する方法を調べていたら、以下の記事を見つけました。

Pythonで複雑なパスワードを簡単に生成する | ガンマソフト株式会社

単純なやり方としては、random.choice()を使う方法がありますが、上の記事ではsecretsモジュールのsecrets.choice()を使っています。

secrets --- 機密を扱うために安全な乱数を生成する — Python 3.8.6 ドキュメント

secrets モジュールを使って、パスワードやアカウント認証、セキュリティトークンなどの機密を扱うのに適した、暗号学的に強い乱数を生成することができます。

インタプリタで実行

$python
>>> import string, secrets
>>> # アルファベット大文字+小文字と数字
>>> chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
>>> ''.join(secrets.choice(chars) for x in range(12))
'lMwUeH4NX36a'
>>> # 空白以外
>>> chars = string.printable.replace(string.whitespace, "")
>>> chars
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> ''.join(secrets.choice(chars) for x in range(12))
']N^1(!Vnd9b:'

f:id:Kurene:20201001194751p:plain

参考(secrets.choice()の正体)

Python Security Module

What is the different between the Random module and the Secrets module? : learnpython

security - How to use Python `secret` module to generate random integer? - Stack Overflow

結局のところ、secretsモジュールはrandom.SystemRandomを使うそうで、これは

オペレーティングシステムの提供する発生源によって乱数を生成する os.urandom() 関数を使うクラスです

Pythonドキュメントに書かれています。

cpython/secrets.py at master · python/cpython · GitHub

cpython/random.py at fa7ce080175f65d678a7d5756c94f82887fc9803 · python/cpython · GitHub

os.urandom

この関数は OS 固有の乱数発生源からランダムなバイト列を生成して返します。この関数の返すデータは暗号を用いたアプリケーションで十分利用できる程度に予測不能ですが、実際のクオリティは OS の実装によって異なります。

On Linux, if the getrandom() syscall is available, it is used in blocking mode: block until the system urandom entropy pool is initialized (128 bits of entropy are collected by the kernel). See the PEP 524 for the rationale.

On Linux, the getrandom() function can be used to get random bytes in non-blocking mode (using the GRND_NONBLOCK flag) or to poll until the system urandom entropy pool is initialized.

On a Unix-like system, random bytes are read from the /dev/urandom device. If the /dev/urandom device is not available or not readable, the NotImplementedError exception is raised.

Windowsで、 CryptGenRandom() を使用します

CryptGenRandom - Wikipedia