這篇文章主要講解了Python如何實現簡單的客戶端認證,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
問題
你想在分布式系統(tǒng)中實現一個簡單的客戶端連接認證功能,又不想像SSL那樣的復雜。
解決方案
可以利用 hmac 模塊實現一個連接握手,從而實現一個簡單而高效的認證過程。下面是代碼示例:
import hmac import os def client_authenticate(connection, secret_key): ''' Authenticate client to a remote service. connection represents a network connection. secret_key is a key known only to both client/server. ''' message = connection.recv(32) hash = hmac.new(secret_key, message) digest = hash.digest() connection.send(digest) def server_authenticate(connection, secret_key): ''' Request client authentication. ''' message = os.urandom(32) connection.send(message) hash = hmac.new(secret_key, message) digest = hash.digest() response = connection.recv(len(digest)) return hmac.compare_digest(digest,response)