Bcrypt

GreenBean·2021년 5월 5일
0
post-thumbnail

Bcrypt

PyPI: Bcrypt

Bcrypt 는 데이터를 단방향 암호화해주는 파이썬 라이브러리

  • hahsing : 원본의 의미를 알 수 없게 섞어놓는 것
  • salting : 실제 비밀번호에 랜덤 값을 더해서 해시값을 계산하는 방법
  • key stretching : 해쉬 값을 여러번 반복해서 해시하는 행위

Bcrypt 에서 암호화할 때는 str 데이터가 아니라 bytes (이진화) 데이터를 이용
즉, 암호화할 때 암호화 할 내용을 bytes화 해줘야 함

파이썬에서 str을 encode하면 bytes가 되고 bytes를 decode하면 str가 됨

  • 파이썬의 인코딩 : 문자열을 바이트 코드인 'utf-8', 'euc-kr', 'ascii' 형식의 바이트 코드로 변환하는 방법
    • 문자열 → 숫자
  • 파이썬의 디코딩 : 인코딩 반대의 역할로써 'utf-8', 'euc-kr', 'ascii' 형식의 바이트 코드를 문자열로 변환하는 방법
    • 숫자 → 문자열

실행 순서

  1. 가상환경 설치 및 실행
conda create -n auth python=3.9
conda activate auth
  1. Bcrypt 설치
pip install bcrypt 
  1. Python 실행
python
  1. Import
import bcrypt

Encode & Decode

  • Example
>>> password = '1234'
>>> bcrypt.hashpw( password, bcrypt.gensalt() )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mihwa/miniconda3/envs/auth/lib/python3.9/site-packages/bcrypt/__init__.py", line 80, in hashpw
    raise TypeError("Unicode-objects must be encoded before hashing")
TypeError: Unicode-objects must be encoded before hashing

>>> encoded_password = password.encode('utf-8')
>>> encoded_password
b'1234'

>>> type(encoded_password)
<class 'bytes'>
>>> type(password)
<class 'str'>

>>> decoded_password = encoded_password.decode('utf-8')
>>> decoded_password
'1234'

Bcrypt Usage

  • Password Hashing
>>> import bcrypt
>>> password = b"super secret password"
>>> # Hash a password for the first time, with a randomly-generated salt
>>> hashed = bcrypt.hashpw(password, bcrypt.gensalt())
>>> # Check that an unhashed password matches one that has previously been
>>> # hashed
>>> if bcrypt.checkpw(password, hashed):
...     print("It Matches!")
... else:
...     print("It Does not Match :(")

hashed = bcrypt.hashpw(password, bcrypt.gensalt())
bcrypt.checkpw(password, hashed)

  • Example
>>> hashed_password = bcrypt.hashpw( password.encode('utf-8'), bcrypt.gensalt() )
>>> hashed_password
b'$2b$12$4P1KNxW7nNWy32Wdn2RD0eZsRk/2EuO8d7pcB5/P.D.2iLpy.yq/y'

>>> bcrypt.gensalt()
b'$2b$12$pgMhUujRGuqAwTon2IhoQe'
>>> bcrypt.gensalt()
b'$2b$12$DQrxH8Y3u4IcIDW/Jj8CDu'
>>> bcrypt.gensalt()
b'$2b$12$H7IPQxywo0m1JzxYY3WDc.'

>>> salt = bcrypt.gensalt()
>>> salt
b'$2b$12$jUOaMuWLk7g67kc5nIox3O'

>>> hashed_password = bcrypt.hashpw( password.encode('utf-8'), salt)
>>> hashed_password
b'$2b$12$jUOaMuWLk7g67kc5nIox3OPpgQ4qAUL1doSjQYc74cYzqGucqZiqC'

>>> type(hashed_password)
<class 'bytes'>

>>> bcrypt.checkpw( '1234'.encode('utf-8'), hashed_password )
True
>>> bcrypt.checkpw( '123'.encode('utf-8'), hashed_password )
False
profile
🌱 Backend-Dev | hwaya2828@gmail.com

0개의 댓글