Marii Marii - 1 year ago 242
PHP Question

Python Cryptography: Cannot sign with RSA private key using PKCS1v15 padding

I'm trying to implement a functionally equivalent signing with Python and the Cryptography library to PHP's

using a SHA1 hash. I've read that PHP uses PKCS1v15 padding, so that's what I'm trying to use as well. My code is:

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

pk = open('key.pem', 'rb')
key = load_pem_private_key(, password=None, backend=default_backend())
message = b'hello world'
signature = key.sign(

Executing this results in:

TypeError Traceback (most recent call last)
<ipython-input-21-ef3db8a6f4a8> in <module>()
3 message,
4 padding.PKCS1v15,
----> 5 hashes.SHA1()
6 )

/home/vagrant/virtualenvs/test/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/ in sign(self, data, padding, algorithm)
614 def sign(self, data, padding, algorithm):
--> 615 signer = self.signer(padding, algorithm)
616 signer.update(data)
617 signature = signer.finalize()

/home/vagrant/virtualenvs/test/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/ in signer(self, padding, algorithm)
551 def signer(self, padding, algorithm):
--> 552 return _RSASignatureContext(self._backend, self, padding, algorithm)
554 def decrypt(self, ciphertext, padding):

/home/vagrant/virtualenvs/test/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/ in __init__(self, backend, private_key, padding, algorithm)
171 if not isinstance(padding, AsymmetricPadding):
--> 172 raise TypeError("Expected provider of AsymmetricPadding.")
174 self._pkey_size = self._backend._lib.EVP_PKEY_size(

TypeError: Expected provider of AsymmetricPadding.

Answer Source

The operator isinstance indicates that padding.PKCS1v15 needs to be an instance instead of the type (class) itself. That means that the object instance should be created by calling the constructor.

To do this add parentheses, i.e. padding.PKCS1v15().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download