본문 바로가기
Python(with Anaconda)

[Python] secrets, string module 이용한 패스워드 생성 프로그램 만들기 (with random)

by moveho 2022. 10. 27.

설계

현대사회를 살아가다 보면 누구나 한 번쯤은 비밀번호 오류로 인해 홈페이지에서 임시로 발급해주는

임시 비밀번호를 받아본 경험이 있을것이다.

그런 것조차 프로그래밍적으로 발급해줬다는 사실조차 놀라운 따름이었다.

임시 비밀번호를 만드는 방법은 다양하게 있지만 이번엔 python random module을 이용해서

만들어보려고 한다.! string module을 사용하여 만들어 보겠다

['Formatter','Template','_ChainMap','__all__','__builtins__','__cached__','__doc__','__file__','__loader__',
 '__name__','__package__','__spec__','_re','_sentinel_dict','_string','ascii_letters','ascii_lowercase',
 'ascii_uppercase','capwords', 'digits', 'hexdigits','octdigits','printable','punctuation','whitespace']

 

string module 에는 다음과 같은 method가 있다.

이 중 ascii_letters, digits, punctuaction 3가지 모듈을 사용해서 만들어보려고 한다.

ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

digits
'0123456789'

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

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

각각 method의 형태이다 3가지의 method를 모두 합쳐 string_pool이라는 변수로 묶어주었다.

 

한국인터넷진흥원에서 권장하는 임시 비밀번호 방법이 있어 그 형태대로 만들어보려고 했다!
권고 임시비밀번호 방법은 바로

" 2가지 이상 문자를 대소문자를 섞고 비밀번호의 총자릿수는 10자리 이상이다"
그래서 이 권고사항에 맞추어 2가지 문자열(ascii_letters, digits)을 포함하면서 10자리 이상의 비밀번호를 만들어 보겠다.

 

찾아보니 python에서는 비밀번호 관리를 위한 secret module을 제공 중이었다!

진작 찾아볼걸 ㅎㅎ

https://docs.python.org/ko/3/library/secrets.html

 

secrets — 비밀 관리를 위한 안전한 난수 생성 — Python 3.11.0 문서

secrets — 비밀 관리를 위한 안전한 난수 생성 소스 코드: Lib/secrets.py secrets 모듈은 암호, 계정 인증, 보안 토큰 및 관련 비밀과 같은 데이터를 관리하는 데 적합한 암호학적으로 강력한 난수를 생

docs.python.org

적극 참조하여 사용해보자!!

 

사용방법 모범사례처럼 string module을 먼저 불러온 후 

secret module을 불러온다!!

import string
import secrets

이렇게 불러오면 모범사례 루틴대로 잘했다

import ascii_letters
import digits
import punctuation

그 후 각각의 method를 불러온다

string_pool = string.ascii_letters + string.digits
while True:
    temp_password = ''.join(secrets.choice(string_pool) for i in range(10))
    if (any(c.islower() for c in temp_password)
        and any(c.isupper() for c in temp_password)
        and sum(c.isdigit() for c in temp_password) >= 3):
temp_password

string_pool 변수를 만들어 ascii_letters와 digits를 합쳐주었다.

while 문으로 난수를 만드는 반복문 시작하고

string_pool에서 랜덤으로으로 문자를 하나씩 선택하고. join()으로 문자열을 붙여서 temp_password변수에 저장

any를 이용해 temp_password 안에 소문자(. islower()) 있는지 확인

(이번에 처음 알았는데 any는 한 가지라도 true 인 것이 있으면 true로 반환하는 함수이다)

마지막으로 temp_password 안에 숫자 문자열. isdigit()  3개 이상 있는지 확인한다.

 

최종 패스워드 출력

우여곡절 성공

그럼 이제 비밀번호를 변경하러 가보자

!

댓글