Bcrypt


Bcrypt


Bcrypt description
Bcryptはパスワードを一方向暗号化するためのPythonライブラリです
  • 郝興:本来の意味を混同
  • Salting:実際のパスワードにランダム値を追加してハッシュ値を計算する方法
  • keystretching:ハッシュ値を複数回繰り返す行為

  • Bcryptでの暗号化にはstrデータではなくバイトデータが使用されます
    つまり、暗号化には暗号化するコンテンツをバイト化する必要がある

    Pythonではstrがバイトに符号化され、バイトがstrに復号される
  • Pythonの符号化:文字列をバイトコード「utf-8」「euc-kr」「ascii」のバイトコードに変換する方法
  • 文字列→数字
  • Pythonの復号化:utf-8、euc-kr、ascii形式のバイトコードを文字列に変換する方法
  • 数字→文字列
  • 実行順序

  • 仮想環境のインストールと実行
  • conda create -n auth python=3.9
    conda activate auth
  • Bcrypt取付
  • pip install bcrypt 
  • Python運転
  • python
  • Library 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