# -*- coding:utf-8 -*-
import json
import base64
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA

def sign_data(data):
    """ 将交易参数转换成签名用的字符串格式 """
    complex_keys = []
    for key, value in data.items():
        if isinstance(value, dict):
            complex_keys.append(key)
    # 将字典类型的数据单独排序
    for key in complex_keys:
        data[key] = json.dumps(data[key], sort_keys=True).replace(" ", "")
    return "&".join("{}={}".format(k, v) for k, v in sorted([(k, v) for k, v in data.items()]))

def sha1_with_rsa(private_key, unsigned_string):
    """ 支付宝用的签名加密 """
    pkey_template = """-----BEGIN PRIVATE KEY-----
    {}
    -----END PRIVATE KEY-----"""
    # 开始计算签名
    key = RSA.importKey(pkey_template.format(private_key))
    signer = PKCS1_v1_5.new(key)
    signature = signer.sign(SHA.new(unsigned_string.encode("utf8")))
    # base64 编码,转换为unicode表示并移除回车
    sign = base64.b64encode(signature).decode("utf8").replace("\n", "")
    return sign