散列函数定义为将大量数据映射到具有指定长度的固定值的函数.此函数确保相同的输入产生相同的输出,实际上定义为哈希和.散列和包括具有特定信息的特征.
此函数几乎无法恢复.因此,任何第三方攻击如蛮力攻击几乎是不可能的.此外,这种算法称为单向加密算法.
理想的加密散列函数有四个主要属性 :
必须很容易计算任何给定输入的哈希值.
生成原始输入必须是不可行的来自它的哈希值.
修改输入而不改变哈希值是不可行的.
找到两个不同的输入是不可行的相同的哈希值.
示例
请考虑以下示例,该示例有助于使用十六进制格式的字符匹配密码./p>
import uuidimport 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')
流程图
我们已经借助以下流程图解释了该程序的逻辑 :
输出
我们的代码将产生以下输出 :
输入的密码两次与哈希函数匹配.这可以确保输入两次的密码准确无误,这有助于收集有用的数据并以加密格式保存.