1

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:

  • Format: x.509;
  • Charset: UTF-8;
  • Encoding: Base64;
  • PKCS1 v1.5;
  • Size: 1024 bits;
  • Message format: SHA-1;

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.

pmatos
  • 276
  • 4
  • 18
  • Your padding specification does not make any sense. OEAP is an encryption padding, not a signature padding. For signatures you can either use PSS or PKCS#1 v1.5 – mat Mar 11 '20 at 09:30
  • Thank you @mat. This totally new for me and really like to see a sample sign code. – pmatos Mar 11 '20 at 10:56
  • Make sure to give correct specification of what you want. Otherwise, no one will be able to give you a sample. – mat Mar 11 '20 at 11:53
  • Dear @mat, thank you once again. I have edited the specifications and hope now are correct. Can you please check? – pmatos Mar 11 '20 at 12:55

1 Answers1

4

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))
mat
  • 1,645
  • 15
  • 36