1. 程式人生 > 程式設計 >Python字串hashlib加密模組使用案例

Python字串hashlib加密模組使用案例

主要用於對字串的加密,最常用的為MD5加密:

import hashlib
def get_md5(data):
  obj = hashlib.md5()
  obj.update(data.encode('utf-8'))
  result = obj.hexdigest()
  return result
val = get_md5('123') #這裡放入要加密的字串文字。
print(val)
#簡便的寫法:
pwd = input('請輸入密碼:').encode('utf-8')
result = hashlib.md5(pwd).hexdigest()
#加鹽寫法:
import hashlib
date = 'hahahah'
ojb = hashlib.md5((date+'123123123').encode('utf-8')).hexdigest()
print(ojb)

如果要避免撞庫的行為,可以加鹽將加密數值改為更加複雜的,這樣破譯起來更加不容易。 

import hashlib
def get_md5(data):
  obj = hashlib.md5('abclasjd;flasdkfhowheofwa123113'.encode('utf-8')) #這裡加鹽
  obj.update(data.encode('utf-8'))
  result = obj.hexdigest()
  return result
val = get_md5('123') #這裡放入要加密的字串文字。
print(val)

案例:

說明:使用者輸入新建的使用者名稱和密碼,以MD5加密的形式存入檔案中。再讓使用者輸入使用者名稱密碼進行匹配。

#!/usr/bin/env python
# _*_ coding=utf-8 _*_
import hashlib
def 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 result
def seve_user(username,password):
  '''
  將加密後的密碼和使用者名稱進行儲存,以| 來分割,檔案為test.txt
  :param username: 需要建立的使用者名稱
  :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 True
while True:
  '''
  迴圈需要建立的使用者
  '''
  user =input('請輸入使用者名稱:')
  if user.upper() == 'N':
    break
  pwd = input('請輸入密碼:')
  if len(user) and len(pwd) < 8:
   print('使用者名稱密碼不符合要求,請重新輸入。')
  else:
    seve_user(user,pwd)
while True:
  '''
  迴圈使用者登入
  '''
  user_name = input('請輸入使用者名稱:')
  password = input('請輸入密碼:')
  start_user = read_user(user_name,get_md5(password))
  if start_user:
    print('登入成功')
    break
  else:
    print('登入失敗')

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。