python加密之hashlib


1、強大的hashlib,提供了用於加密相關的操作,代替了md5模塊和sha模塊,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

2、hmac模塊實現了hmac算法,需要一個key來進行加密,提供更為強大的加密,不過需要提供key,也就是通常說的鹽

3、使用hashlib.algorithms_available,可以查看hashlib提供的加密算法

4、加密的算法的一般使用,但時候存在缺陷,即:通過撞庫可以反解

# ######## md5 ########
hash = hashlib.md5()  #創建md5()加密實例
hash.update(bytes('admin', encoding='utf-8'))  #對admin字符進行加密
print(hash.hexdigest()) #返回產生的十六進制的bytes
print(hash.digest()) 
 
 
######## sha1 ########
 
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 ########
 
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())
 1 Hash objects have these methods:
 2  - update(arg): Update the hash object with the bytes in arg. Repeated calls
 3                 are equivalent to a single call with the concatenation of all
 4                 the arguments.
 5  - digest():    Return the digest of the bytes passed to the update() method
 6                 so far.
 7  - hexdigest(): Like digest() except the digest is returned as a unicode
 8                 object of double length, containing only hexadecimal digits.
 9  - copy():      Return a copy (clone) of the hash object. This can be used to
10                 efficiently compute the digests of strings that share a common
11                 initial substring.
官方說明

5、添加添加自定義key再來做加密

import hashlib
 
# ######## md5 ########
 
hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8"))
hash.update(bytes('admin',encoding="utf-8"))
print(hash.hexdigest())

6、直接使用hmac

import hmac
 
h = hmac.new(bytes('898oaFs09f',encoding="utf-8"))
h.update(bytes('admin',encoding="utf-8"))
print(h.hexdigest())

7、自定義密碼加密模塊

 1 #!/usr/bin/env python
 2 # -*- coding: utf8 -*-
 3 # __Author: "Skiler Hao"
 4 # date: 2017/4/9 15:26
 5 import hashlib
 6 from hashlib import sha256
 7 import random
 8 import hmac
 9 
10 
11 def _create_salt():
12     salt = sha256(str(random.random()).encode('utf-8')).hexdigest()[-8:]
13     return salt
14 
15 
16 def set_password(password,salt = None):
17     if not salt:
18         salt = _create_salt()
19     hashed_pwd = hmac.new(bytes(salt, encoding=("utf-8")))
20     hashed_pwd.update(bytes(password, encoding=("utf-8")))
21     return hashed_pwd.hexdigest()+'$'+salt
22 
23 
24 def check_pwd(pwd, hashed_pwd_salt):
25     hashed_pwd,salt = hashed_pwd_salt.split('$')
26     new_hash_pwd_salt = set_password(pwd,salt)
27     if new_hash_pwd_salt == hashed_pwd_salt:
28         return True
29     else:
30         return False
mypassword

8、對Web的api添加認證,增加安全性:

客戶端:基於SECRET_KEY和時間,進行md5加密,生成動態的auth_key

1 # 用於API認證的KEY,直接在settings配置,注意安全,不要隨意泄露給它人
2 KEY = '299095cc-1330-11e5-b06a-a45e60bec08b'
settings
 1     def auth_key(self):
 2         """
 3         用於生成auth_key,對key進行封裝
 4         :return: 將加密后的動態key以字典形式返回
 5         """
 6         key = hashlib.md5(self.key.encode('utf-8'))  # 將key作為鹽先放進去,增加復雜度
 7         auth_time = time.time()  # 獲取當前時間,混入其中
 8         key.update(bytes("%s|%f" % (key, auth_time), encoding='utf-8'))
 9         encryption_key = key.hexdigest()
10         result = "%s|%f" % (encryption_key, auth_time)
11         # 可以將key放入request的headers部分,由於鍵不能為下划線,建議使用-
12         return {'auth-key': result}
客戶端的加密過程

服務器端: 

 驗證步驟:

    1、驗證時間是否過期,設置為5s,或者在settings里面配置

1 ASSET_AUTH_KEY = '299095cc-1330-11e5-b06a-a45e60bec08b'
2 ASSET_AUTH_HEADER_NAME = 'HTTP_AUTH_KEY'
3 ASSET_AUTH_TIME = 2  # 默認時間為秒
settings

    2、收到的auth_key進行解密驗證

    3、3s內訪問過的加入list禁止再次訪問

def api_auth_validation(request):

    # 從請求的header部分拿到encryption_key
    encryption_key_timestamp = request.META.get('HTTP_AUTH_KEY')
    # 拿不到則直接報錯
    if not encryption_key_timestamp:
        return False

    sp = encryption_key_timestamp.split('|')
    # 檢查加密后的key,和時間是否用|隔開樣式是否正確
    if len(sp) != 2:
        return False
    # 拿到加密后的key和request時間
    encryption_key,request_time = sp
    request_time = float(request_time)

    current_server_time = time.time()
    # 時間失效,或者請求的時間戳是未來的,都報錯
    if current_server_time - ASSET_AUTH_EXPIRE_TIME > request_time | current_server_time < request_time:
        return False

    # 拿到服務器存儲的key進行加密驗證
    ha = hashlib.md5(ASSET_AUTH_KEY.encode('utf-8'))
    ha.update(bytes("%s|%f")%(ASSET_AUTH_KEY,request_time))
    result = ha.hexdigest()
    # 如果不等的話直接返回False
    if result != encryption_key:
        return False
    exist = False
    del_keys = []
    # 拿到ENCRYPT_LIST,判斷是否訪問過
    for k,v in enumerate(ENCRYPT_LIST):
        print(k,v)
        m = v['time']
        n = v['encrypt']
        
        if m < current_server_time - ASSET_AUTH_EXPIRE_TIME:
            # 如果超時加入要刪除的列表,做好刪除准備
            del_keys.append(k)
            continue
        if n == encryption_key:
            # 是否有存在的內容
            exist = True
    for k in del_keys:
        del ENCRYPT_LIST[k]
    if exist:
        return False
    # 驗證完全通過加入到ENCRYPT_LIST
    ENCRYPT_LIST.append({'encrypt':encryption_key,'time':request_time})
    # 最后再返回True
    return True
具體方法

 

 

 

如有轉載,請標明出處,如有任何建議,請留言


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM