老师博客:http://www.cnblogs.com/Eva-J/articles/8244551.html#_label6

server端

import socket
import os
import hmac
server=socket.socket()
ip_port=('192.168.43.155',8888)
server.bind(ip_port)
server.listen()
client,addr=server.accept()
secret_key=bytes('lhy'.encode('utf-8'))
def checkout():
    random=os.urandom(32)#返回的bytes类型
    secret_info=hmac.new(secret_key,random)
    server_secret = secret_info.digest()#返回的是bytes
    client.send(random)
    client_secret=client.recv(1024)
    if client_secret==server_secret:
        print('检验成功,合法的客户端')
        check_out='true'
    else:
        print('不合法的客户端')
        check_out='false'
    client.send(bytes(check_out.encode('utf-8')))
checkout()

 

client端

import socket
import hmac
client=socket.socket()
ip_port=('192.168.43.155',8888)
client.connect(ip_port)
secret_key=bytes('lhy'.encode('utf-8'))
def checkout():
    msg=client.recv(1024)
    secret_msg=hmac.new(secret_key,msg)
    client_secret=secret_msg.digest()
    client.send(client_secret)
    check_out=client.recv(1024).decode('utf-8')
    if check_out=='true':
        print('合法的客户端')
    else:
        print('不合法的客户端')
checkout()

 

这只是很简单的客户端的合法验证,只是小小的写了一下而已。值得注意的是os.urandom和digest返回的都是bytes类型的数据。所以发送的接受的时候都不需要encode

下面来看看hashlib的客户端的验证方式。

server端

import socket
import os
import hashlib
server=socket.socket()
ip_port=('192.168.43.155',8888)
server.bind(ip_port)
server.listen()
client,addr=server.accept()
secret_key=bytes('lhy'.encode('utf-8'))
def checkout():
    random=os.urandom(32)#返回的bytes类型
    secret_info=hashlib.md5(secret_key)
    secret_info.update(random)
    server_secret = secret_info.hexdigest()#返回的是bytes
    client.send(random)
    client_secret=client.recv(1024).decode('utf-8')
    if client_secret==server_secret:
        print('检验成功,合法的客户端')
        check_out='true'
    else:
        print('不合法的客户端')
        check_out='false'
    client.send(bytes(check_out.encode('utf-8')))
checkout()

 

client端

import socket
import hashlib
client=socket.socket()
ip_port=('192.168.43.155',8888)
client.connect(ip_port)
secret_key=bytes('lhy'.encode('utf-8'))
def checkout():
    msg=client.recv(1024)
    secret_msg=hashlib.md5(secret_key)
    secret_msg.update(msg)
    client_secret=secret_msg.hexdigest().encode('utf-8')
    client.send(client_secret)
    check_out=client.recv(1024).decode('utf-8')
    if check_out=='true':
        print('合法的客户端')
    else:
        print('不合法的客户端')
checkout()

 

这代码几乎和hmac一模一样,注意的是hashlib必需hash的是bytes,返回的确实str的类型。而hmac无论hash还是返回的值都是bytes类型