Python 取證 - 雜湊函式



雜湊函式定義為將大量資料對映為具有指定長度的固定值的一個函式。此函式可確保相同的輸入得到相同的結果,而該結果實際上定義為雜湊和。雜湊和包括帶有特定資訊的特徵。

實際上不可能反轉此函式。因此,任何第三方攻擊(如暴力攻擊)實際上都是不可能的。此外,這種演算法稱為單向加密演算法

理想的加密雜湊函式具有四個主要屬性 -

  • 對任何給定的輸入計算雜湊值都必須容易。
  • 從其雜湊值生成原始輸入必須不可行。
  • 修改輸入而不更改雜湊值必須不可行。
  • 找到具有相同雜湊值的兩個不同的輸入必須不可行。

示例

考慮以下示例,它有助於使用十六進位制格式的字元匹配密碼。

import uuid
import hashlib
  
def hash_password(password):
   # userid is used to generate a random number
   salt = uuid.uuid4().hex #salt is stored in hexadecimal value
   return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt
     
def check_password(hashed_password, user_password):
   # hexdigest is used as an algorithm for storing passwords
   password, salt = hashed_password.split(':')
   return password == hashlib.sha256(salt.encode()
      + user_password.encode()).hexdigest()

new_pass = raw_input('Please enter required password ')
hashed_password = hash_password(new_pass)
print('The string to store in the db is: ' + hashed_password)
old_pass = raw_input('Re-enter new password ')

if check_password(hashed_password, old_pass):
   print('Yuppie!! You entered the right password')
else:
   print('Oops! I am sorry but the password does not match')

流程圖

我們藉助以下流程圖解釋了此程式的邏輯 -

Hash Function Flowchart

輸出

我們的程式碼將產生以下輸出 -

Hash Function Output

兩次輸入的密碼與雜湊函式匹配。這可確保兩次輸入的密碼準確無誤,這有助於收集有用的資料並以加密格式儲存它們。

廣告