hash模塊 hashlib不可逆加密 和 base64算法加密解密

hashlib模塊 

  1. 用於加密相關的操做,代替md5模塊和sha模塊,主要提供SHA1,SHA224,SSHA256,SHA384,SHA512,MD5算法  
  2. 直接看代碼案例: 

---------md5----------- html

hash = hashlib.md5()  
hash.update(bytes('admin',encoding='utf-8'))  
hash.update(bytes('123',encoding='utf-8'))
print(hash.hexdigest()) 

print(hash.digest())

----------sha1--------- python

hash = hashlib.sha1()  
hash.update(bytes('admin',encoding='utf-8'))  
print(hash.hexdigest())  

----------sha256------- 算法

hash = hashlib.sha256()  
hash.update(bytes('admin',encoding='utf-8'))  
print(hash.hexdigest())

---------sha384-------- app

hash = hashlib.sha384()  
hash.update(bytes("admin",encoding='utf-8'))  
print(hash.hexdigest())  

------------sha512-------- 編碼

hash = hashlib.sha512()  
hash.update(bytes('admin',encoding='utf-8'))  
print(hash.hexdigest())  

 注意  

以上加密算法雖然很是厲害,但有時存在缺陷,即:經過撞庫能夠反解。  加密

因此,有必要對加密算法中添加自定義key再來加密 spa

hash = hashlib.md5(bytes('790dfhdfe3',encoding='utf-8'))  
hash.update(bytes('admin',encoding='utf-8'))  
print(hash.hexdigest())  
-------------------------------  
python 內置還有一個hmac模塊,它內部對咱們建立key和內容進行進一步的處理而後再加密  
import hmac  
h = hmac.new(bytes('dfew3',encoding="utf-8"))  
h.update(bytes('admin',encoding="utf-8"))  
print(h.hexdigest())  
  

 計算獲得文件md5值code

def MD5(file):
    import hashlib
    md5_value = hashlib.md5()
    with open(file, 'rb') as file:
        while True:
            data = file.read(2048)
            if not data:
                break
            md5_value.update(data)
    return md5_value.hexdigest()



ret = MD5(r"C:\Users\Administrator\Desktop\aaaa\cgss2008append.dta")
print(ret)

 

Base64加密解密方法

base64代碼博文連接:http://www.cnblogs.com/txw1958/archive/2012/07/19/python3-base64.htmlhtm

import base64

copyright = 'Copyright (c) 2012 Doucube Inc. All rights reserved.'

def main():
    #轉成bytes string
    bytesString = copyright.encode(encoding="utf-8")
    print(bytesString)

    #base64 編碼
    encodestr = base64.b64encode(bytesString)
    print(encodestr)
    print(encodestr.decode())

    #解碼
    decodestr = base64.b64decode(encodestr)
    print(decodestr.decode())


if __name__ == '__main__':
    main()
相關文章
相關標籤/搜索