socketserver hashlib hmac

1. socketserver: 网络协议的最底层就是socket,基于原有socket模块,又封装了一层,就是socketserver, socketserver 为了实现tcp协议,server端的并发.

# 服务端
# 用socketserver解决TCP的并发问题
import socketserver
class Myserver(socketserver.BaseRequestHandler):
    def handle(self):
        conn = self.request  # 由socketserver封装好的连接对象
        addr = self.client_address  # 由socketserver封装好的客户端IP端口号
        while True:
            res = conn.recv(1024)
            print(res.decode())

            strvar = input("服务端给客户端的消息: ")
            conn.send(strvar.encode())

            if strvar.upper() == "Q":
                break

server = socketserver.ThreadingTCPServer(("127.0.0.1",9000),Myserver)
server.serve_forever()



# 客户端
import socket
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
while True:
    strvar = input("客户端给服务端的消息: ")
    sk.send(strvar.encode())

    res = sk.recv(1024)
    if res.upper() == b"Q":
        break
    print(res.decode())

sk.close()

 

2. hashlib模块: 这个模块是一堆加密算法的集合体,哈希算法的加密方式不止一种.哈希算法也叫摘要算法,相同的数据始终得到相同的输出,不同的数据得到不同的输出.

https://www.cmd5.com/ md5解密网站

import hashlib
# 1. 创建一个md5算法的对象
hs = hashlib.md5()
# 2. 把要加密的数据通过update更新到hs对象中运算
hs.update("今天天气不错!".encode("utf-8")) # 里面的数据需转换成二进制字节流
# 3. 获取32位的十六进制的字符串
res = hs.hexdigest()
print(res, len(res))
# 6abad61b6c635c28f65237cc10633c9d 32

# 加盐(加一个关键字配合原字符串,让密码更加复杂,不容易破解)
hs = hashlib.md5("加盐关键字".encode("utf-8"))
hs.update("今天天气不错".encode("utf-8"))
res = hs.hexdigest()
print(res, len(res))
# 306212c24f8aadbbaf3547ca280f9f6d 32

# 动态加盐
import random
num = random.randrange(10)
b_word = chr(random.randrange(65,91))
s_word = chr(random.randrange(97,123))
lst = [num,b_word,s_word]
key_lst = random.sample(lst,3)
key = str(key_lst)
print(key) # ['Q', 'k', 6]

hs = hashlib.md5(key.encode("utf-8"))  # md5加密算法速度稍快,但是安全性一般
hs.update("今天天气不错".encode("utf-8"))
res = hs.hexdigest()
print(res, len(res))
# a47abd6ba40e3fb0fd7d9a2fd9055df3 32

hs = hashlib.sha224()  # sha加密算法速度稍慢,但是安全性较高
hs.update("今天天气不错".encode())
res = hs.hexdigest()
print(res, len(res))
# b61a712d8c6712a48513092cda18a91291f734bf9bd430da410fe758 56

hs = hashlib.sha512()
hs.update("今天天气不错".encode())
res = hs.hexdigest()
print(res, len(res))
# 5c70d47381a5631fa9912d152b13a066e387e5cbfdca2fc47e05ff1217bf29d2b7930d73576f7eb71780baad3a2dde6bb0075fd6ab9fb8a12f11f9fb51846d0a 128

 

3. hmac模块: 算法更加复杂,不容易破解

import hmac
key = "加盐".encode()
msg = "今天天气不错".encode()
hm = hmac.new(key,msg)
res = hm.hexdigest()
print(res, len(res))
# 3339c19e0c535dc72148957352173885 32

# 动态加盐
# 方式一:
import random
num = random.randrange(10)
b_word = chr(random.randrange(65,91))
s_word = chr(random.randrange(97,123))
lst = [num,b_word,s_word]
key_lst = random.sample(lst,3)

key = str(key_lst).encode()
msg = "今天天气不错".encode()

hm = hmac.new(key,msg)
res = hm.hexdigest()
print(res, len((res)))
# 13051eeeaf99a22dd32a366a5cafe908 32

# 方式二:
import os
key = os.urandom(32) # 返回随机的二进制字节流, 参数:代表的长度
msg = "今天天气不错".encode()
hm = hmac.new(key,msg)
res = hm.hexdigest()
print(res, len(res))
# 39edbcf1109a51d05f59386d6bb5b241 32

 

4. 案例之根据hashlib模块进行文件校验

# 文件校验
# 小文件
import hashlib
def check_file(file):
    with open(file,mode="rb") as fp:
        hs = hashlib.md5()
        hs.update(fp.read())
    return hs.hexdigest()

res1 = check_file("D:\python学习\上课代码\day29--socketserver, hashlib, hmac\作业.txt")
res2 = check_file("D:\python学习\上课代码\day29--socketserver, hashlib, hmac\作业 - 副本.txt")
print(res1, res2)
# 09e928cf9048a274cbec915a9c96f7a4 09e928cf9048a274cbec915a9c96f7a4

# 大文件
# 方式一:
def check_file(file):
    hs = hashlib.md5()
    with open(file,mode="rb") as fp:
        while True:
            # 一次最多读取1024个字节
            content = fp.read(1024)
            if content:
                # 将读出的字节分批更新计算
                hs.update(content)
            else:
                break
        return hs.hexdigest()
res1 = check_file("D:\python学习\上课代码\day29--socketserver, hashlib, hmac\作业.txt")
res2 = check_file("D:\python学习\上课代码\day29--socketserver, hashlib, hmac\作业 - 副本.txt")
print(res1, res2)
# 09e928cf9048a274cbec915a9c96f7a4 09e928cf9048a274cbec915a9c96f7a4

# 方式二: import os def check_file(file): hs = hashlib.md5() file_size = os.path.getsize(file) with open(file,mode="rb") as fp: while file_size: content = fp.read(1024) hs.update(content) file_size -= len(content) return hs.hexdigest() res1 = check_file("D:\python学习\上课代码\day29--socketserver, hashlib, hmac\作业.txt") res2 = check_file("D:\python学习\上课代码\day29--socketserver, hashlib, hmac\作业 - 副本.txt") print(res1, res2) # 09e928cf9048a274cbec915a9c96f7a4 09e928cf9048a274cbec915a9c96f7a4

 

 

5. 案例之服务器合法性检验

# 服务器合法性检验案例
# 服务器(提供接口)
import os
import hmac
import socket
def auth(conn,secret_key):
    msg = os.urandom(32)
    conn.send(msg)
    hm = hmac.new(secret_key.encode(),msg)
    res_serve = hm.hexdigest()
    print(res_serve)
    res_client = conn.recv(1024).decode()

    if res_serve == res_client:
        print("是合法的连接用户")
        return True
    else:
        print("不是合法的连接用户")
        return False

sk = socket.socket()
sk.bind(("127.0.0.1",9000))
sk.listen()
conn,addr = sk.accept()
secret_key = "秘钥值"

res = auth(conn,secret_key)
if res:
    print(conn.recv(1024).decode())

conn.close()
sk.close()


# 服务器(使用接口)
import socket
import hmac

def auth(secret_key,sk):
    msg = sk.recv(32)
    hm = hmac.new(secret_key.encode(),msg)
    res = hm.hexdigest()
    print(res)
    sk.send(res.encode())

secret_key = "秘钥值"
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
auth(secret_key,sk)

sk.send("请求使用这个服务器的接口".encode())
sk.close()

 

posted on 2020-06-08 18:11  fdsimin  阅读(184)  评论(0编辑  收藏  举报