python实现SHA256WithRSA和SHA256WithPss

荣耀渠道支付修改了加密算法,签名算法由"SHA256withRSA"变更为"SHA256withRSA/PSS",所以需要增加
python实现SHA256WithRSA和SHA256WithPss_第1张图片

SHA256WithRSA

    @classmethod
    def SHA256WithRSA(cls, data, file_name=""):
        from Crypto.Signature import PKCS1_v1_5 as pk
        curPath = os.path.abspath(os.path.dirname(__file__))
        if file_name == "":
            file_name = "private_bak"
        pkcs8_private_key = RSA.importKey(open(curPath + f'/key_file/{file_name}.pem', 'r').read())
        h = SHA256.new(data)
        signer = pk.new(pkcs8_private_key)
        signature = signer.sign(h)
        return base64.b64encode(signature).decode()

SHA256WithPss

    @classmethod
    def SHA256WithPss(cls, data, file_name=""):
        from Crypto.Signature import PKCS1_PSS as pk
        curPath = os.path.abspath(os.path.dirname(__file__))
        if file_name == "":
            file_name = "private_bak"
        pkcs8_private_key = RSA.importKey(open(curPath + f'/key_file/{file_name}.pem', 'r').read())
        h = SHA256.new(data)
        signer = pk.new(pkcs8_private_key)
        signature = signer.sign(h)
        return base64.b64encode(signature).decode()

不同点:
from Crypto.Signature import PKCS1_v1_5 as pk
from Crypto.Signature import PKCS1_PSS as pk

备注:
刚开始SHA256WithPss用的是以下方法(百度也大部分是这种方式):

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.backends import default_backend

from cryptography.hazmat.primitives.serialization import load_pem_private_key, load_pem_public_key

def rsa_pss_sign(private_key_path, message):
    # 从 PEM 格式的私钥文件中加载私钥
    with open(private_key_path, "rb") as key_file:
        private_key = load_pem_private_key(key_file.read(), password=None, backend=default_backend())

    # 使用 RSA-PSS 算法生成签名
    signature = private_key.sign(
        message.encode("utf-8"),
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )

    return signature.hex()

private_key_path = "private_key.pem"
message = "待签名的数据"

signature = rsa_pss_sign(private_key_path, message)
print("Signature:", signature)

用这个方式加密出来的数据不对,就去看SHA256WithRSA中的Signature 包,发现有pss
python实现SHA256WithRSA和SHA256WithPss_第2张图片

你可能感兴趣的:(问题解决,Python基础,python高阶编程,python,开发语言)