Python 密碼學模組



在本章中,您將詳細瞭解 Python 中各種密碼學模組。

密碼學模組

它包含所有配方和原語,並提供 Python 編碼的高階介面。您可以使用以下命令安裝密碼學模組:

pip install cryptography

PIP Install

程式碼

您可以使用以下程式碼來實現密碼學模組:

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)

輸出

上面給出的程式碼產生以下輸出:

Authentication

此處提供的程式碼用於驗證密碼並建立其雜湊值。它還包括用於驗證密碼以進行身份驗證的邏輯。

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 - 如果您輸入了正確的密碼,您可以找到以下輸出:

Correct Password

場景 2 - 如果我們輸入錯誤的密碼,您可以找到以下輸出:

Wrong Password

解釋

Hashlib 包用於在資料庫中儲存密碼。在此程式中,使用salt,它在實現雜湊函式之前將隨機序列新增到密碼字串中。

廣告