#导入base64模块来进行base64编码 import base64 import rsa import time class HandleSign: # 定义服务器公钥, 往往可以存放在公钥文件中,通过抓包获取 server_pub = """ -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQENQujkLfZfc5Tu9Z1LprzedE O3F7gs+7bzrgPsMl29LemonPYvIG8C604CprLittlenJpnhWu2lGirlWZyLq6sBr tuPorOc42+gInFfyhJAwdZB6Sqlove7bW+jNe5youDtU7very6Gx+muchGo8Dg+S kKlZFc8Br7SHtbL2tQIDAQAB -----END PUBLIC KEY----- """ @classmethod def to_encrypt(cls, msg, pub_key=None): """ 非对称加密 :param msg: 待加密字符串或者字节 :param pub_key: 公钥 :return: base64密文字符串 请求参数:{"key1":"value1","key2":"value2"} + 字段时间戳 + token前50位 通过公钥去解密 加密后拿到一个字符:w9cVcJvpx8+dgqKnEUgaim {"key1":"value1","key2":"value2","sign": "w9cVcJvpx8+dgqKnEUgaim"} """ if isinstance(msg, str): # 如果msg为字符串, 则转化为字节类型 msg = msg.encode('utf-8') elif isinstance(msg, bytes): # 如果msg为字节类型, 则无需处理 pass else: # 否则抛出异常 raise TypeError('msg必须为字符串或者字节类型!') if not pub_key: # 如果pub_key为空, 则使用全局公钥 pub_key = cls.server_pub.encode("utf-8") elif isinstance(pub_key, str): # 如果pub_key为字符串, 则转化为字节类型 pub_key = pub_key.encode('utf-8') elif isinstance(pub_key, bytes): # 如果msg为字节类型, 则无需处理 pass else: # 否则抛出异常 raise TypeError('pub_key必须为None、字符串或者字节类型!') public_key_obj = rsa.PublicKey.load_pkcs1_openssl_pem(pub_key) # 创建 PublicKey 对象 # 2.创建 PublicKey 对象 # public_key_obj = rsa.PublicKey.load_pkcs1(pub_key) cryto_msg = rsa.encrypt(msg, public_key_obj) # 生成加密文本 cipher_base64 = base64.b64encode(cryto_msg) # 将加密文本转化为 base64 编码 result = cipher_base64.decode() # 将字节类型的 base64 编码转化为字符串类型 return result @classmethod def generate_sign(cls, token): """ 生成sign,对外使用 :param timestamp:当前秒级时间戳,为int类型 :param token: token,为str类型 :return: 时间戳和sign组成的字典 """ timestamp = int(time.time()) # 获取当前的时间戳 print(timestamp) prefix_50_token = token[:50] # 获取token前50位 message = prefix_50_token + str(timestamp) # 将token前50位与时间戳字符串进行拼接 sign = cls.to_encrypt(message) # 生成sign return {"timestamp": timestamp, "sign": sign} if __name__ == '__main__': # 数据传递加密场景:待加密字符串或者字节 love_talk = "admin@123" # 1.用自己生成的publickye测试下 # lemon_pub,lemon_priv=rsa.newkeys(512) # lemon_pub2=lemon_pub.save_pkcs1() # print(lemon_pub2) # 调用to_encrypt类方法来进行加密 cryto_info = HandleSign.to_encrypt(msg=love_talk) print(cryto_info) # 开放鉴权场景:请求入参中中加入sign字段,拿到新的请求参数发送请求 sign = HandleSign.generate_sign(token="fb432a51-a252-410b") print(sign)
标签:base64,RSA,pub,sign,token,key,msg,非对称,鉴权 From: https://www.cnblogs.com/python-test001/p/18117777