Bcrypt
11782 ワード
Bcrypt
Bcrypt description
Bcryptはパスワードを一方向暗号化するためのPythonライブラリです
Bcryptでの暗号化にはstrデータではなくバイトデータが使用されます
つまり、暗号化には暗号化するコンテンツをバイト化する必要がある
Pythonではstrがバイトに符号化され、バイトがstrに復号される
実行順序
conda create -n auth python=3.9
conda activate auth
pip install bcrypt
python
import bcrypt
Encode & Decode
>>> 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
>>> 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)
>>> 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
Reference
この問題について(Bcrypt), 我々は、より多くの情報をここで見つけました https://velog.io/@hwaya2828/Bcryptテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol