我正在尝试将我的代码从Python 2.7迁移到Python 3.5
以下是当前在Python 2.7中使用M2Crypto的实现
import M2Crypto
import hashlib
from binascii import hexlify
# Generates the signature of payload
def getSign(payload_xml):
# SHA-1 digest of the payload
dig = myDigest(payload_xml)
# Loading the privateKey PEM file
private_key = M2Crypto.RSA.load_key('privatekey')
# Generating base 16 and encoding
signature = hexlify(private_key.private_encrypt(dig, M2Crypto.RSA.pkcs1_padding))
return signature
# To generate sha-1 digest of payload
def myDigest(payload):
# This will give base 16 of SHA-1 digest
digest_1 = hashlib.sha1(payload).hexdigest()
return digest_1
sign = getSign(<mypayload_xml>)
这是使用pycryptodome在Python 3.5中的新实现。
from Crypto.PublicKey import RSA
import hashlib
from Crypto.Cipher import PKCS1_v1_5
from binascii import hexlify
def myDigest(payload):
# This will give base 16 of SHA-1 digest
digest_1 = hashlib.sha1(payload.encode('utf-8')).hexdigest()
return digest_1
def getSign(payload_xml):
# SHA-1 digest of the payload
dig = myDigest(payload_xml)
with open('privatekey', 'r') as pvt_key:
miPvt = pvt_key.read()
rsa_key_obj = RSA.importKey(miPvt)
cipher = PKCS1_v1_5.new(rsa_key_obj)
cipher_text = cipher.encrypt(dig.encode())
base_16_new = hexlify(cipher_text)
return base_16_new
new_sign = getSign(<mypayload_xml>)
然而,对于相同的有效负载,签名是不同的。有人能帮忙提供正确的解决方案吗?
Cipher
类的encrypt
和decrypt
方法只允许使用公钥进行加密和私钥进行解密,即 PyCryptodome 没有与您使用的 M2Crypto 的private_encrypt
和public_decrypt
方法一一对应的方法(而是 PyCryptodome 具有Signature
类的签名和验证方法)。因此,在 Python 3.6 代码中,仅使用公钥加密负载的 SHA1 哈希值(即使应用了私钥,也仅使用公钥部分)。这是纯加密而不是签名。 - Topaco