Python ---MD5 加密

1、md5加密的目的:密碼不能明文存儲,需要密文存儲。python中加密模塊hashlib。
2、撞庫:md5加密後是不可解密的,網絡上提供給解密使用了撞庫,即字符串逐個試,撞庫只能破解弱密碼。
3、普通加密代碼:

import hashlib
plaintext_str = 'abcdef'
# 創建md5實例化對象
obj = hashlib.md5()
# 寫入要加密的字節
obj.update(plaintext_str.encode("utf-8"))
# 獲取密文
ciphertext_str = obj.hexdigest()
print('明文:%s  轉換成密文:%s'%(plaintext_str, ciphertext_str))
"""
執行結果:
明文:abcdef  轉換成密文:e80b5017098950fc58aad83c8c14978e
"""

4、爲防止撞庫操作,提高安全性的方法進行‘加鹽‘
5、加鹽是指在你輸入的密碼後面再加一個隨機字符串。
加鹽md5加密代碼:

def md5(plaintext_str, salt=''):
    # 生成明文+加鹽的新字符串
    new_plaintext_str = plaintext_str + salt
    # 實例化md5對象
    obj = hashlib.md5()
    # 寫入要加密的字節
    obj.update(new_plaintext_str.encode('utf-8'))
    # 獲取密文
    ciphertext_str = obj.hexdigest()
    # 返回密文
    return ciphertext_str

plaintext_str = 'abcdef'
salt = '111'
result = md5(plaintext_str, salt)
print('明文:%s  加鹽%s 轉換成密文:%s'%(plaintext_str, salt, result))
"""
執行結果:
明文:abcdef  加鹽111 轉換成密文:87915233455e55b7ba4d1e359f518779
"""
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章