標籤:模組 雜湊 ems __name__ 讀取 www. lse def import
Python 產生雜湊hash--hashlib模組
1)產生hash並儲存在本地
(1)代碼
[python] view plain copy
import hashlib
import shelve
#原密碼paw={"water":"123456","root":"admin123"}
#產生hash
m1 = hashlib.md5("123456".encode("utf-8"))
m2 = hashlib.md5("admin123".encode("utf-8"))
h1 = m1.hexdigest()
h2 = m2.hexdigest()
print(h1)
print(h2)
#現在利用shelve儲存帳號和密碼資訊到本地
db1 = shelve.open("E:/Python_Code/work/hash_dic")
db1["water"] = h1
db1["admin"] = h2
(2)輸出
e10adc3949ba59abbe56e057f20f883e
0192023a7bbd73250516f069df18b500
2)模仿登陸
上面我們已經產生密碼資訊的雜湊值,並且用shelve庫儲存到了本地,現在是時候使用它了。
(1)代碼
[python] view plain copy
import hashlib
import shelve
#從shelve檔案中讀取使用者資訊
db1 = shelve.open("E:/Python_Code/work/hash_dic")
#退出系統
def tuichu():
print("正在退出系統...")
exit("期待下次與您相遇!")
# 操作函數,依據使用者名稱給予不同的許可權
def caozuo(user_name):
if user_name=="admin":
tuichu() #測試用
else:
tuichu() #測試用
#登入函數
def login():
for i in range(3): #只有3次登入機會
user_name = input("帳號:")
user_pass = input("密碼:")
m = hashlib.md5(user_pass.encode("utf-8"))
hash_pass = m.hexdigest()
for ku,vu in db1.items():
if user_name == ku and hash_pass == vu:
print("登入成功!歡迎您{}!".format(ku))
#這裡可以執行操作函數
caozuo(user_name)
break
else:
print("帳號或密碼錯誤!您還有{}次機會!".format(2-i))
continue
else:
print("今日登入次數已經用完!")
if __name__ == ‘__main__‘:
login()
文:http://www.ylsjwang.com/dianshiju/24.html
(2)運行
Python 產生雜湊hash--hashlib模組