이 기사에서는 암호로 효과적으로 사용할 수 있는 안전한 난수를 생성하는 방법을 살펴보겠습니다. 무작위 숫자와 함께 문자 및 기타 문자를 추가하여 더 좋게 만들 수도 있습니다.
비밀
secrets 모듈에는 for 루프 및 범위 기능을 사용하여 필요한 길이의 암호를 생성하는 데 사용할 수 있는 선택이라는 기능이 있습니다.
예
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 모듈을 사용합니다.
예
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 모듈에서 아래 방법을 사용할 수 있습니다.
예
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