Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python secrets 모듈로 안전한 난수와 비밀번호 생성하기

이 글에서는 비밀번호로 효과적으로 사용할 수 있는 안전한 난수를 생성하는 방법을 알아봅니다. 단순한 숫자만으로 구성된 난수보다는 문자와 특수문자를 함께 조합하면 훨씬 더 강력한 비밀번호를 만들 수 있습니다.

일반적인 random 모듈은 예측 가능성이 있어 보안 목적으로는 적합하지 않습니다. 따라서 암호학적으로 안전한 난수가 필요할 때는 파이썬의 secrets 모듈을 사용하는 것이 권장됩니다.

secrets 모듈로 비밀번호 생성하기

secrets 모듈에는 choice() 함수가 내장되어 있으며, for 루프와 range() 함수를 함께 사용하면 원하는 길이의 비밀번호를 손쉽게 생성할 수 있습니다.

예제 코드

import secrets
import string
allowed_chars = string.ascii_letters + string.digits + string.printable
pswd = ''.join(secrets.choice(allowed_chars) for i in range(8))
print("The generated password is: \n",pswd)

실행 결과

The generated password is:
$pB7WY

대소문자와 숫자 포함 조건 추가하기

비밀번호에 소문자, 대문자, 숫자가 반드시 포함되도록 조건을 강제할 수도 있습니다. 마찬가지로 secrets 모듈을 사용하며, while 루프를 통해 조건을 만족하는 비밀번호가 나올 때까지 반복 생성합니다.

예제 코드

import secrets
import string
allowed_chars = string.ascii_letters + string.digits + string.printable
while True:
    pswd = ''.join(secrets.choice(allowed_chars) for i in range(8))
    if (any(c.islower() for c in pswd) and any(c.isupper()
        for c in pswd) and sum(c.isdigit() for c in pswd) >= 3):
        print("The generated pswd is: \n", pswd)
        break

실행 결과

The generated pswd is:
p7$7nS2w

URL용 랜덤 토큰 생성하기

웹 개발에서 비밀번호 재설정 링크처럼 URL에 무작위 토큰을 포함해야 하는 경우가 많습니다. 이럴 때 secrets 모듈이 제공하는 아래 세 가지 메서드를 활용할 수 있습니다.

  • token_bytes() : 무작위 바이트 문자열 생성
  • token_hex() : 16진수 형태의 무작위 텍스트 문자열 생성
  • token_urlsafe() : URL에 안전하게 사용할 수 있는 텍스트 토큰 생성

예제 코드

import secrets
# A random byte string
tkn1 = secrets.token_bytes(8)
# A random text string in hexadecimal
tkn2 = secrets.token_hex(8)
# random URL-safe text string
url = 'https://thename.com/reset=' + secrets.token_urlsafe()
print("A random byte string:\n ",tkn1)
print("A random text string in hexadecimal: \n ",tkn2)
print("A text string with url-safe token: \n ",url)

실행 결과

A random byte string:
b'\x0b-\xb2\x13\xb0Z#\x81'
A random text string in hexadecimal:
d94da5763fce71a3
A text string with url-safe token:
https://thename.com/reset=Rd8eVookY54Q7aTipZfdmz-HS62rHmRjSAXumZdNITo

마무리

secrets 모듈은 암호학적으로 안전한 난수를 제공하기 때문에 비밀번호 생성, 인증 토큰, 세션 키 등 보안이 중요한 작업에 적합합니다. 일반 용도의 난수라면 random 모듈로 충분하지만, 보안 관련 기능을 개발할 때는 반드시 secrets 모듈을 사용하는 습관을 들이는 것이 좋습니다.