단방향 해시 함수 - bcrypt

Nam Eun-Ji·2020년 11월 30일
0
import bcrypt

>>> pw = 'hello1234'
>>> a = bcrypt.hashpw(pw.encode('utf-8'), bcrypt.gensalt())
b'$2b$12$v3fc59a2Xz4WtoQ2EfpPouVGI.xCcW1NX49.UdkzQHIc2c12dyJnC'

>>> b = bcrypt.hashpw(pw.encode('utf-8'), bcrypt.gensalt())
b'$2b$12$T/OO/oRVFsxn3pAZwGGjJOFZiH1W1yXtHM7PVM.KIeJb1ifGRq.N6'

설치

pip install bcrypt


장단점

bcrypt는 솔팅, 키스트레칭을 통해 해시함수의 취약점에 대비하지만 결국에는 트레이드오프이다. 해킹에 대비하여 솔팅, 키 스트레칭을 추가한 것이 사용자가 로그인할 때마다 그만큼의 작업을 서버가 수행해야 하기 때문이다.



다른 단방향해시함수와 다른 점

????

bc

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 :(")

KDF

import bcrypt
key = bcrypt.kdf(
    password=b'password',
    salt=b'salt',
    desired_key_bytes=32,
    rounds=100
)

Adjustable Work Factor

import bcrypt
password = b"super secret password"
# Hash a password for the first time, with a certain number of rounds
hashed = bcrypt.hashpw(password, bcrypt.gensalt(14))
# Check that a unhashed password matches one that has previously been
# hashed
if bcrypt.checkpw(password, hashed):
    print("It Matches!")
else:
    print("It Does not Match :(")

Maximum Password Length
bcrypt 알고리즘은 패스워드를 72자까지만 처리하며, 그 이상의 문자는 무시된다. 이 문제를 해결하기 위해, 일반적인 접근방식은 암호 해시(예: sha256)로 암호를 해싱한 후 brypt로 결과를 해내기 전에 NULL 바이트 문제를 방지하기 위해 base64를 인코딩하는 것이다.

password = b"an incredibly long password" * 10
hashed = bcrypt.hashpw(
    base64.b64encode(hashlib.sha256(password).digest()),
    bcrypt.gensalt()
)

Python bcrypt cost factor
해싱 속도를 늦춤으로써 보안을 강화한다.

import bcrypt
import time

passwd = b's$cret12'

start = time.time()
salt = bcrypt.gensalt(rounds=16)
hashed = bcrypt.hashpw(passwd, salt)
end = time.time()

print(end - start)     # 4.268407821655273    해시생성시간 측정
print(hashed)          # b'$2b$16$.1FczuSNl2iXHmLojhwBZO9vCfA5HIqrONkefhvn2qLQpth3r7Jwe'



참고 사이트
https://d2.naver.com/helloworld/318732
https://blog.benpri.me/blog/2019/01/13/why-you-shouldnt-be-using-bcrypt-and-scrypt/
http://www.codeok.net/%ED%8C%A8%EC%8A%A4%EC%9B%8C%EB%93%9C%20%EB%B3%B4%EC%95%88%EC%9D%98%20%EA%B8%B0%EC%88%A0

profile
한 줄 소개가 자연스러워지는 그날까지

0개의 댓글