Python字符串hashlib加密模塊使用案例
主要用于對字符串的加密,最常用的為MD5加密:
import hashlibdef get_md5(data): obj = hashlib.md5() obj.update(data.encode(’utf-8’)) result = obj.hexdigest() return resultval = get_md5(’123’) #這里放入要加密的字符串文字。print(val)
#簡便的寫法:pwd = input(’請輸入密碼:’).encode(’utf-8’)result = hashlib.md5(pwd).hexdigest()
#加鹽寫法:import hashlibdate = ’hahahah’ojb = hashlib.md5((date+’123123123’).encode(’utf-8’)).hexdigest()print(ojb)
如果要避免撞庫的行為,可以加鹽將加密數(shù)值改為更加復(fù)雜的,這樣破譯起來更加不容易。
import hashlibdef get_md5(data): obj = hashlib.md5(’abclasjd;flasdkfhowheofwa123113’.encode(’utf-8’)) #這里加鹽 obj.update(data.encode(’utf-8’)) result = obj.hexdigest() return resultval = get_md5(’123’) #這里放入要加密的字符串文字。print(val)
案例:
說明:用戶輸入新建的用戶名和密碼,以MD5加密的形式存入文件中。再讓用戶輸入用戶名密碼進行匹配。
#!/usr/bin/env python# _*_ coding=utf-8 _*_import hashlibdef get_md5(data): ’’’ 登錄加密,將傳入的密碼進行加密處理,并返回值。 :param data: 用戶的密碼 :return: 返回MD5加密后的密碼 ’’’ obj = hashlib.md5(’abclasjd;flasdkfhowheofwa123113’.encode(’utf-8’)) #這里加鹽 obj.update(data.encode(’utf-8’)) result = obj.hexdigest() return resultdef seve_user(username,password): ’’’ 將加密后的密碼和用戶名進行保存,以| 來分割,文件為test.txt :param username: 需要創(chuàng)建的用戶名 :param password: MD5后的密碼 :return: 需要更改的地方,return判斷是否保存成功。 ’’’ user_list = [username,get_md5(password)] lis = ’|’.join(user_list) with open(’test.txt’,encoding=’utf-8’,mode=’a’)as f: f.write(lis+’n’)def read_user(username,password): ’’’ 來判斷用戶登錄所輸入的用戶名和是否正確。 :param username: 用戶輸入的用戶名 :param password: MD5加密后的密碼 :return: 如果匹配返回True ’’’ with open(’test.txt’,mode=’r’,encoding=’utf-8’) as f: for item in f: infomation = item.strip() user,pwd = infomation.split(’|’) if username == user and password == pwd:return Truewhile True: ’’’ 循環(huán)需要創(chuàng)建的用戶 ’’’ user =input(’請輸入用戶名:’) if user.upper() == ’N’: break pwd = input(’請輸入密碼:’) if len(user) and len(pwd) < 8: print(’用戶名密碼不符合要求,請重新輸入。’) else: seve_user(user,pwd)while True: ’’’ 循環(huán)用戶登錄 ’’’ user_name = input(’請輸入用戶名:’) password = input(’請輸入密碼:’) start_user = read_user(user_name,get_md5(password)) if start_user: print(’登錄成功’) break else: print(’登錄失敗’)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JS算法題解旋轉(zhuǎn)數(shù)組方法示例2. SpringBoot集成SSM、Dubbo、Redis、JSP的案例小結(jié)及思路講解3. Python語言規(guī)范之Pylint的詳細用法4. springboot用controller跳轉(zhuǎn)html頁面的實現(xiàn)5. python中pandas.read_csv()函數(shù)的深入講解6. VMware如何進入BIOS方法7. python爬蟲利用代理池更換IP的方法步驟8. PHP設(shè)計模式之迭代器模式Iterator實例分析【對象行為型】9. Python如何解決secure_filename對中文不支持問題10. WMLScript腳本程序設(shè)計第1/9頁
