问题
I am migrating a service from Python 2.7 to Python 3.5 which communicated with another service using RSA encryption/decryption.
Python(v2.7) m2crypto(0.25.1) < Correct Signature >
key = M2Crypto.RSA.load_key(private_key)
digest = hashlib.sha1(bytes(cipher_text, encoding="UTF-8")).hexdigest()
signature = hexlify(key.private_encrypt(digest, M2Crypto.RSA.pkcs1_padding))
Python(v3.5) rsa(v3.4.2)
pri_key = rsa.PrivateKey.load_pkcs1(private_key)
signature = hexlify(rsa.sign(cipher_text.encode(), pri_key, "SHA-1"))
Signature produced by above codes are different. What is the difference between these packages?
回答1:
You are executing different cryptographic operations. encrypt with private key != digital signature
signature = hexlify(key.private_encrypt(digest, M2Crypto.RSA.pkcs1_padding))
and
signature = hexlify(rsa.sign(cipher_text.encode(), pri_key, "SHA-1"))
A digital signature with PCKS#1 v1.5 makes a RSA encryption on digest algorithm identifier and the digest of the message encoded in ASN.1
signature =
RSA_Encryption(
ASN.1(DigestAlgorithmIdentifier + SHA1(message) ))
While encryption does not include the digest algorithm identifier
Seems Python key.private_encrypt
is a wrapper on openssl RSA_private_encrypt Take a look to the warning about thepkcs1_padding
you are using
RSA_PKCS1_PADDING
PKCS #1 v1.5 padding. This function does not handle the algorithmIdentifier specified in PKCS #1. When generating or verifying PKCS #1 signatures,
RSA_sign(3)
andRSA_verify(3)
should be used.
You should use sign
and not private_encrypt
for digital signatures. But if you want encryption to hide the content of the message, you should use encryption with the public key, not the private.
来源:https://stackoverflow.com/questions/45320041/rsa-signature-is-different-generated-from-rsa-module-and-m2crypto