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

人盡茶涼 提交于 2021-01-04 07:12:51

问题


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())

回答1:


You mention you are running an outdated version.

Upgrading from version 1.7.1 to 2.6.1 resolves the issue.



来源:https://stackoverflow.com/questions/55291174/error-in-python-cryptography-module-rsaprivatekey-object-has-no-attribute-si

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!