这篇文章主要讲解了Python如何实现简单的客户端认证,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
问题
你想在分布式系统中实现一个简单的客户端连接认证功能,又不想像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)