–
下面是http非安全方式进行服务端和客户端通信的示例,保证第一次秘钥的安全性,以及后续报文的完整性
import hashlib import base64 import time from Crypto.Cipher import AES CREATE_TOKEN_KEY = '5mGyVEdPX5efeOHQRcd183a211ed2434' AES_SECRET_KEY = 'eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZ' class AESEncrypt(object): def __init__(self): self.key = AES_SECRET_KEY self.mode = AES.MODE_ECB def add_to_16(self, value): while len(value) % 16 != 0: value += '\0' return str.encode(value) def encrypt(self, text): cryptor = AES.new(self.add_to_16(self.key), self.mode) encrypt_aes = cryptor.encrypt(self.add_to_16(text)) return str(base64.b64encode(encrypt_aes), encoding='utf-8') def decrypt(self, text): decode = base64.b64decode(text.encode()) cryptor = AES.new(self.add_to_16(self.key), self.mode) decrypt_aes = str(cryptor.decrypt(decode), encoding='utf-8').replace('\0','') return decrypt_aes def create_token(username): if username == '': print('create_token: username is request') return None sha256 = hashlib.sha256(str(CREATE_TOKEN_KEY+username).encode('utf-8')) token = sha256.hexdigest() return token class HttpSignatureSend(object): def __init__(self): self.host = 'kubernetes.andblog.com' self.path = '/api/' self.timestamp = str(int(time.time())) self.signature = '' self.username = '' self.body = '{"email":"admin@andblog.com","treePathDesc":"互联网产品技术平台.技术中心.运维部.应用组"}' def create(self, username, token): self.username = username data = '{host}\n{path}\n{timestamp}\n{body}\n{token}\n{username}' \ .format(host=self.host, path=self.path, timestamp=self.timestamp, body=self.body, token=token, username=self.username) sha256 = hashlib.sha256(str(data).encode('utf-8')) self.signature = sha256.hexdigest() print(data) print(self.signature) class HttpSignatureReceive(object): def __init__(self): self.host = '' self.path = '' self.timestamp = '' self.signature = '' self.username = '' self.body = '' def verify(self): token = create_token(self.username) data = '{host}\n{path}\n{timestamp}\n{body}\n{token}\n{username}' \ .format(host=self.host, path=self.path, timestamp=self.timestamp, body=self.body, token=token, username=self.username) sha256 = hashlib.sha256(str(data).encode('utf-8')) result = sha256.hexdigest() if result == self.signature: return True else: return False if __name__ == '__main__': token = create_token('kubernetes-api-user') print(token) aes_encrypt = AESEncrypt() encode = aes_encrypt.encrypt(token) print(encode) decode = aes_encrypt.decrypt(encode) print(decode) print('send http request') http_send = HttpSignatureSend() http_send.create('kubernetes-api-user', create_token('kubernetes-api-user')) print('receive http request') http_receive = HttpSignatureReceive() http_receive.host = http_send.host http_receive.path = http_send.path http_receive.timestamp = http_send.timestamp http_receive.signature = http_send.signature http_receive.username = http_send.username http_receive.body = http_send.body result = http_receive.verify() print(result)
–
–
–
评论前必须登录!
注册