Pythonによる安全なランダムパスワード生成の実践例

パスワードはアカウントやデータを守るための重要な要素であり、十分な強度を持つことが求められる。本記事では、Pythonを用いて安全かつ多様なランダムパスワードを生成する方法を紹介する。

パスワードの要件

強力なパスワードには以下の特徴が求められる:

  • 最低8文字以上
  • 大文字・小文字・数字・記号(!@#$%など)を含む
  • 辞書単語や連続・繰り返し文字を避ける
  • 個人情報(生年月日、名前など)を含まない

secretsモジュールによる安全なパスワード生成

secretsモジュールは暗号論的に安全な乱数を生成するため、パスワード生成に最適である。

import secrets
import string

def create_secure_password(length=12):
    charset = string.ascii_letters + string.digits + "!@#$%^&*"
    return ''.join(secrets.choice(charset) for _ in range(length))

print(create_secure_password())

出力例:

K9@mQ!vL2#xP

randomモジュールによるパスワード生成(非推奨)

randomモジュールは予測可能性があるため、セキュリティ要件が高い場面では使用すべきではないが、テスト用途などには使える。

import random
import string

def create_weak_password(length=10):
    pool = string.ascii_lowercase + string.digits
    return ''.join(random.choices(pool, k=length))

print(create_weak_password())

出力例:

n3k9q2m7x1

特定文字種のみで構成されるパスワード

以下は、文字種ごとにパスワードを生成する例である。

# 英字のみ
def letters_only(length=8):
    return ''.join(secrets.choice(string.ascii_letters) for _ in range(length))

# 数字のみ
def digits_only(length=6):
    return ''.join(secrets.choice(string.digits) for _ in range(length))

# 記号のみ
def symbols_only(length=5):
    symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?"
    return ''.join(secrets.choice(symbols) for _ in range(length))

カスタムパスワード生成関数

各文字種を必ず1文字以上含むように設計された関数:

def generate_strong_password(length=12):
    if length < 4:
        raise ValueError("Minimum length is 4")
    
    pwd = [
        secrets.choice(string.ascii_lowercase),
        secrets.choice(string.ascii_uppercase),
        secrets.choice(string.digits),
        secrets.choice("!@#$%^&*")
    ]
    
    all_chars = string.ascii_letters + string.digits + "!@#$%^&*"
    for _ in range(length - 4):
        pwd.append(secrets.choice(all_chars))
    
    secrets.SystemRandom().shuffle(pwd)
    return ''.join(pwd)

print(generate_strong_password(14))

出力例:

aB3$kL9!mNqW2x

タグ: Python secrets random password-generation

5月17日 07:24 投稿