Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in python cryptography module: _RSAPrivateKey' object has no attribute 'sign

In my Python code, I'm using cryptography module. I have a private key on disk. So, from documentation, I used this example to load that key. Then use that key to sign a message. But running the program throws AttributeError: '_RSAPrivateKey' object has no attribute 'sign'

I looked in to source code of serialization module and check return type of load_pem_private_key(). The code requires some understanding of Abstract Base Classes.

Seeking help here to debug this issue.

Here's my code

  1 from cryptography.hazmat.backends import default_backend
  2 from cryptography.hazmat.primitives import hashes
  3 from cryptography.hazmat.primitives import serialization
  4 from cryptography.hazmat.primitives.asymmetric import padding
  5 from cryptography.hazmat.primitives.asymmetric import utils
  6 
  7 from base64 import b64encode
  8 
  9 def test_new_crypto():
 10     privkey = '/path/to/privkey'
 11     with open(privkey, "rb") as kf:
 12         private_key = serialization.load_pem_private_key(
 13                 kf.read(),
 14                 password=None,
 15                 backend=default_backend()
 16                 )
 17 
 18     message = b"A message I want to sign"
 19     signature = private_key.sign(  #### Error is here
 20             message,
 21             padding.PSS(
 22                 mgf=padding.MGF1(hashes.SHA256()),
 23                 salt_length=padding.PSS.MAX_LENGTH
 24                 ),
 25             hashes.SHA256()
 26             )
 27 
 28     return b64encode(signature)
 29 
 30 if __name__ == "__main__":
 31     print(test_new_crypto())
like image 322
Bhaskar Avatar asked Apr 08 '26 01:04

Bhaskar


2 Answers

You mention you are running an outdated version.

Upgrading from version 1.7.1 to 2.6.1 resolves the issue.

like image 87
dusk Avatar answered Apr 09 '26 15:04

dusk


If you are here in 2022 and you use PyJWT, in cryptography version 37 the signer methods were deprecated, so you have to downgrade to version 36.0.2 of cryptography.

like image 41
montty Avatar answered Apr 09 '26 16:04

montty