Cryptography-with-python-modules-of-cryptography

提供:Dev Guides
移動先:案内検索

暗号化のPythonモジュール

この章では、Pythonの暗号化のさまざまなモジュールについて詳しく学習します。

暗号化モジュール

すべてのレシピとプリミティブが含まれており、Pythonでのコーディングの高レベルインターフェイスを提供します。 次のコマンドを使用して暗号化モジュールをインストールできます-

pip install cryptography

PIPインストール

Code

次のコードを使用して暗号化モジュールを実装できます-

from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt("This example is used to demonstrate cryptography module")
plain_text = cipher_suite.decrypt(cipher_text)

出力

上記のコードは、次の出力を生成します-

認証

ここで指定されたコードは、パスワードを検証し、そのハッシュを作成するために使用されます。 また、認証目的でパスワードを検証するためのロジックも含まれています。

import uuid
import hashlib

def hash_password(password):
   # uuid is used to generate a random number of the specified password
   salt = uuid.uuid4().hex
   return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt

def check_password(hashed_password, user_password):
   password, salt = hashed_password.split(':')
   return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()

new_pass = input('Please enter a password: ')
hashed_password = hash_password(new_pass)
print('The string to store in the db is: ' + hashed_password)
old_pass = input('Now please enter the password again to check: ')

if check_password(hashed_password, old_pass):
   print('You entered the right password')
else:
   print('Passwords do not match')

出力

  • シナリオ1 *-正しいパスワードを入力した場合、次の出力を見つけることができます-

正しいパスワード

  • シナリオ2 *-間違ったパスワードを入力した場合、次の出力を見つけることができます-

間違ったパスワード

説明

*Hashlib* パッケージは、データベースにパスワードを保存するために使用されます。 このプログラムでは、ハッシュ関数を実装する前にパスワード文字列にランダムシーケンスを追加する *salt* が使用されます。