0
0

DjangoとPythonのsecretsを使ってパスワードの自動生成・ハッシュ化をしよう

Posted at

概要

Djangoにはmake_random_password()というメソッドがあるのですが非推奨なので今回は公式で推奨されているsecretsを使ったパスワード生成方法を使用します
また、ハッシュ化はDjangoにある機能を使って行います

今回はDjangoのshellを使って自動生成します
secretsとstringをimportし、メソッドを実行します

poetry run python manage.py debugsqlshell
Python 3.11.2 (main, Mar 23 2023, 14:09:52) [GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import string
>>> import secrets
>>> alphabet = string.ascii_letters + string.digits + string.punctuation
>>> password = ''.join(secrets.choice(alphabet) for i in range(16))
>>> password
'i,Id1DtX$y5dNLo('
  • ascii_letters
  • digits
  • punctuation

の中身は以下の通りです

>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

また、range内の数字でパスワードの長さを調整できます

パスワードのハッシュ化

fixtureを使う際にパスワードをハッシュ化する際はDjangoのmake_passwordメソッドを使います
make_passwordメソッドの中に先ほど自動生成したパスワードを入れます

>>> from django.contrib.auth.hashers import make_password
>>> make_password('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
'pbkdf2_sha256$600000$QcH0cm6kihyD7LCU3vL0XG$bcnfLwTFLzewYJj14xIhErzDY82qK57KRLLu0I7p6Ew='

以上です

参考

0
0
1

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
0