pmatos
pmatos

Reputation: 296

Using pycryptodome or cryptography in python 3.6. How to achieve this?

Imagine the following message:

"This is a message to the signed"

I have the need to sign this sample message using "pycryptodome" or "cryptography" in Python 3.6 with the following standards:

I have the required "privatekey.pem" but I do not know how to do do it in pycryptodome or cryptography.

UPDATED: I have found this sample code but still not know if it is the correct way to achieve what I need based on standards defined on the original message. The sample code (for pycryptodome):

from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA1
import base64
from base64 import b64encode, b64decode

key = open('privatekey.pem', "r").read()
rsakey = RSA.importKey(key)
signer = PKCS1_v1_5.new(rsakey)
digest = SHA1.new()
data = 'This the message to be signed'
digest.update(b64decode(data))
sign = signer.sign(digest)
doc = base64.b64encode(sign)
print(doc)

I can see that I get a 172 characters signature hash but need professional advise to know if this meets the standards I described and if it is the correct way of doing it.

Upvotes: 1

Views: 1578

Answers (1)

mat
mat

Reputation: 1717

Here is a code snippet, adapted from the applicable documentation page:

from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA1
from Crypto.PublicKey import RSA
from base64 import b64encode

message = 'This the message to be signed'
key = RSA.import_key(open('private_key.der').read())
h = SHA1.new(message)
signature = pkcs1_15.new(key).sign(h)
print(b64encode(signature))

Upvotes: 5

Related Questions