Flask-bcrypyt


๐Ÿ’ก ๋น„๋ฐ€๋ฒˆํ˜ธ ์•ˆ์ „ํ•˜๊ฒŒ ์ €์žฅํ•˜๊ธฐ

์•”ํ˜ธ๋ฅผ ์žˆ๋Š” ๊ทธ๋Œ€๋กœ DB์— ์ €์žฅํ•˜๋ฉด ๋ณด์•ˆ์ƒ ๋ฌธ์ œ๊ฐ€ ์ƒ๊ธด๋‹ค.

๊ทธ๋ž˜์„œ ์˜ค๋Š˜์€ Flask-bcrpyt๋ฅผ ์‚ฌ์šฉํ•ด๋ดค๋‹ค.

# __init__.py
from flask_bcrypt import Bcrypt

bcrypt = Bcrypt()

def create_app():
    app = Flask(__name__)
    #bcrypt
    bcrypt.init_app(app)

    return app
password = "test"

# ์•”ํ˜ธํ™”
encrypted_password = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()) 
#=> b'$2b$12$/vf/wF1/4dMU1G5OV.RrSOl6YwG1HyXr/xt05tiH9oMxsJShb7QZm'

# db์— ์ €์žฅํ•  ๋•Œ๋Š” strํ˜•ํƒœ๋กœ ์ €์žฅ.
encrypted_password.decode("utf-8")
#=> $2b$12$/vf/wF1/4dMU1G5OV.RrSOl6YwG1HyXr/xt05tiH9oMxsJShb7QZm


๐Ÿ’ก 12.22 ์ถ”๊ฐ€ ๋‚ด์šฉ

์ถ”๊ฐ€์ ์œผ๋กœ check_password_hash๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋กœ๊ทธ์ธ์‹œ ์•”ํ˜ธ๊ฐ€ ๋งž๋Š”์ง€ ์•„๋‹Œ์ง€ ํ™•์ธํ•  ๋•Œ์—๋Š”

์•„๋ž˜์™€ ๊ฐ™์ด ํ™•์ธํ•ด ์ค€๋‹ค. ๋ฐ˜ํ™˜ ๊ฐ’์€ True ํ˜น์€ False ์˜€๋‹ค.

# db์— strํ˜•ํƒœ๋„ ์ €์žฅ๋˜์–ด ์žˆ๋Š” ๋น„๋ฐ€๋ฒˆํ˜ธ
db_password = '$2b$12$/vf/wF1/4dMU1G5OV.RrSOl6YwG1HyXr/xt05tiH9oMxsJShb7QZm'

# (str โ†’ byte-string) 
db_password = bytes(db_password, encoding = "utf-8")
#=> b'$2b$12$/vf/wF1/4dMU1G5OV.RrSOl6YwG1HyXr/xt05tiH9oMxsJShb7QZm'

# ๋กœ๊ทธ์ธ์‹œ ์ž…๋ ฅํ•œ ๋น„๋ฐ€๋ฒˆํ˜ธ์™€ DB์— ์ €์žฅ๋˜์–ด ์žˆ๋Š” ๋น„๋ฐ€๋ฒˆํ˜ธ ๋น„๊ต.
bcrypt.chect_password_hash(input_pw.encode('utf-8'), db_password)
#=> True

๊ทธ๋ฆฌ๊ณ  ์ฒซ ๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ์™€, ๋‘ ๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ ๋ชจ๋‘ byte-string์„ ๋„ฃ์–ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

ํ–ˆ๋˜ ์‹ค์ˆ˜ : byte-string์„ ๋„ฃ์–ด์ฃผ์ง€ ์•Š์Œ.


๐Ÿ“š Reference