1. 程式人生 > >python----常用模組(hashlib加密,Base64,json)

python----常用模組(hashlib加密,Base64,json)

一、hashlib模組

1.1 hashlib模組,主要用於加密相關的操作,在python3的版本里,代替了md5和sha模組,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 演算法。
加密需要先例項化MD5物件,再將字串轉成bytes型別(加密必須得是bytes型別,不能直接對字串加密)進行加密,且md5是不可逆的!

m =hashlib.md5()#例項化md5物件

passwd ='ytt123456'

# passwd.encode()#把字串轉成bytes型別
#加密必須得是bytes型別
m.update(passwd.encode())#
不能直接對字串加密,要先把字串轉成bytes型別 print(m.hexdigest()) #md5是不可逆的

1.2 將加密寫成一個函式如下:

def my_md5(str):

    new_str = str.encode()#字串轉成bytes型別

    #new_str = b'%s'%str##字串轉成bytes型別

    m = hashlib.md5()#例項化md5物件

    m.update(new_str)#加密

    return m.hexdigest()#獲取結果返回


二、Base64 是一種用64個字元來表示任意二進位制資料的方法

import base64

s='hahaha'

byte_s = s.encode() #字串變成二進位制

res = base64.b64encode(byte_s) #base64編碼

print(res.decode()) #把bytes轉成字串。
#列印結果:aGFoYWhh

jie_mi_res = base64.b64decode(res.decode()) #base64編碼

print(jie_mi_res.decode())
#輸出結果:hahaha

 

三、json模組

import json

#json串是一個字串

f 
= open('product',encoding='utf-8') res = f.read() print(json.loads(res))#字串變成字典 product_dic = json.loads(res)#把字串,變成python的資料型別 print(type(product_dic)) print(product_dic.get('product_info')) print(json.load(f))#傳一個檔案物件,它會幫你讀檔案
d = {
    'zll':{
        'addr':'北京',
        'age':28
    },
    'ljj':{
        'addr':'北京',
        'age':38
    }
}

fw = open('user_info.json','w',encoding='utf-8')

dic_json = json.dumps(d,ensure_ascii=False,indent=4)#字典轉成json,字典轉成字串
                         #顯示為中文          縮排4格
print(dic_json)

fw.write(dic_json)

json.dump(d,fw,ensure_ascii=False,indent=4)#操作檔案,自動幫你寫了

3.1 json檔案小練習

import json
def op_data(filename,dic=None):
    if dic:#字典不為空,寫入
        with open(filename,'w',encoding='utf-8') as fw:
            json.dump(dic,fw,ensure_ascii=False,indent=4)#操作檔案,自動幫你寫了
    else:
        with open(filename,encoding='utf-8') as fr:
            return json.load(fr)#傳一個檔案物件,它會幫你讀檔案
FILE_NAME = 'user_info.json'
all_users =op_data('user_info.json')
print(all_users)
for i in range(3):
    choice = input('輸入,1註冊,2刪除')
    if choice =='1':
        username = input('username:')
        pwd = input('pwd:')
        if username not in all_users:
           all_users[username] =pwd
           op_data(FILE_NAME,all_users)
    elif choice =='2':
        username =input('username:')
        all_users.pop(username)
        op_data(FILE_NAME,all_users)