python生成RSA签名

# -*- coding: utf-8 -*-
# Auth :yuyu

# pip install -i https://pypi.douban.com/simple/ pycryptodome
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
import base64
import os

'''不分段'''
def get_sgin(out_trade_no=None,type=None,price=None,pay_password=None,phone=None,public_data=None):

    if out_trade_no:
        msg = "out_trade_no={}&price={}&pay_password={}".format(out_trade_no, price, pay_password)
    else:
        msg = "type={}&info=2&phone={}&app_id=com.jiutongfuwu.wantcashier".format(type, phone)
    # 读取文件中的公钥
    key = open(public_data).read()  #文件的公钥
    publickey = RSA.importKey(key)
    # 进行加密
    pk = PKCS1_v1_5.new(publickey)
    encrypt_text = pk.encrypt(msg.encode())
    # 加密通过base64进行编码
    result = base64.b64encode(encrypt_text)
    result = str(result, encoding="utf-8")  # byte类型转换为str
    return result

# if __name__ == '__main__':
#     public_data ='public.pem'
#     res =get_sgin(type=1,public_data =public_data)
#     print(res)

'''分段'''
def join_sgin(data,public_data): # data 是参数
    key =open(public_data).read()
    publickey =RSA.importKey(key)
    #分段
    pk = PKCS1_v1_5.new(publickey)
    encrypt_text =[]

    for i in range(0,len(data),100):
        context = data[i,i+100]
        encrypt_text.append(pk.encrypt(context.encode()))
        cipher_text = b''.join(encrypt_text)
        #加密通过base64
        result = base64.b64encode(cipher_text)
        result =str(result,encoding= 'utf-8')
        return result

 

posted @ 2021-05-31 23:30  快乐的平头哥  阅读(412)  评论(0编辑  收藏  举报