Python字符串hashlib加密模塊使用案例
主要用于對(duì)字符串的加密,最常用的為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)
#簡(jiǎn)便的寫法:pwd = input(’請(qǐng)輸入密碼:’).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加密的形式存入文件中。再讓用戶輸入用戶名密碼進(jìn)行匹配。
#!/usr/bin/env python# _*_ coding=utf-8 _*_import hashlibdef get_md5(data): ’’’ 登錄加密,將傳入的密碼進(jìn)行加密處理,并返回值。 :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): ’’’ 將加密后的密碼和用戶名進(jìn)行保存,以| 來分割,文件為test.txt :param username: 需要?jiǎng)?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)需要?jiǎng)?chuàng)建的用戶 ’’’ user =input(’請(qǐng)輸入用戶名:’) if user.upper() == ’N’: break pwd = input(’請(qǐng)輸入密碼:’) if len(user) and len(pwd) < 8: print(’用戶名密碼不符合要求,請(qǐng)重新輸入。’) else: seve_user(user,pwd)while True: ’’’ 循環(huán)用戶登錄 ’’’ user_name = input(’請(qǐng)輸入用戶名:’) password = input(’請(qǐng)輸入密碼:’) start_user = read_user(user_name,get_md5(password)) if start_user: print(’登錄成功’) break else: print(’登錄失敗’)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算2. 詳解idea中web.xml默認(rèn)版本問題解決3. JSP頁面實(shí)現(xiàn)驗(yàn)證碼校驗(yàn)功能4. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫的方法5. jsp EL表達(dá)式詳解6. asp知識(shí)整理筆記4(問答模式)7. ASP實(shí)現(xiàn)加法驗(yàn)證碼8. python selenium 獲取接口數(shù)據(jù)的實(shí)現(xiàn)9. java 優(yōu)雅關(guān)閉線程池的方案10. Python matplotlib 繪制雙Y軸曲線圖的示例代碼
