我正在尝试为有效负载生成签名。我的技术栈在 Python3.6 中,它提供了密码学或 pycrypto 之类的库。问题是,我无法private_encrypt
在密码学等库中重新创建 M2Crypto 的功能。M2Crypto 生成的签名被我的对端接受为有效签名,而由两个库生成的签名被丢弃,说无效签名。
我已经使用 python2.7 创建了一个最小的 POC 来说明我的情况。
import base64
payload = b'This is the payload for which I wish to generate signature'
### Using library cryptography ###
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
with open("private_key", "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(),
password=None,
backend=default_backend()
)
signature = private_key.sign(
payload,
padding=padding.PKCS1v15(),
algorithm=hashes.SHA1()
)
encoded_signature = base64.b16encode(signature)
print("Signature using cryptography - ", encoded_signature)
### Using library pycrypto ###
from Crypto.Signature import PKCS1_v1_5, PKCS1_PSS
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
key = RSA.importKey(open('private_key').read())
h = SHA.new(payload)
signer = PKCS1_v1_5.new(key)
signature = signer.sign(h)
encoded_signature = base64.b16encode(signature)
print("Signature using pycrypto - ", encoded_signature)
### Using M2Crypto ###
import hashlib
import M2Crypto
digest = hashlib.sha1(payload).hexdigest()
private_key = M2Crypto.RSA.load_key('./private_key')
# Encrypt digest using private key and encode in Hex (Base16)
encoded_signature = base64.b16encode(private_key.private_encrypt(
digest, M2Crypto.RSA.pkcs1_padding))
print("Signature using M2Crypto - ", encoded_signature)
cryptography
由和创建的签名Crypto
相同,与由 生成的签名不同M2Crypto
。TIA。