rsa implementation question

Bryan Olson fakeaddress at
Wed Aug 11 10:21:22 CEST 2004

Ajay Brar asked:
 > i am using RSa for signing documents and hence decrypting and then
 > encrypting to verify?

Unfortunately yes, that seems to be what pycrypto is doing.
The method is now discredited.

 > what i was rather trying to get at was what if the plaintext is too
 > large?

Always hash and pad, for any size message.  I suggest the SHA-1,
hash function, which is in the Python standard library as "sha".

Next you need a padding scheme that formats the message into a
block suitable for the RSA private key operation.  The signing
method of PKCS#1 version 1.5 is the most popular RSA signature
scheme, and when the payload is a hash digest it has no known
serious weaknesses.

The function encode_block_from_message, below, will hash a given
message, then build and return a EMSA-PKCS1-v1_5 "Encoded
Message" (EM) from it.  The returned EM is suitable for signing
with the pycrypto RSA sign function.

I agree with about half of Heiko Wundram's response.

#  sha1_header_tuple is the prefix of the DER encoding of a:
#     sequene(sequence(oid, NULL), octet_string)
#  where the octet string has length 20, and completes the encoding.
sha1_header_tuple = (0x30, 0x21, 0x30, 0x9, 0x6, 0x5, 0x2b, 0xe,
         0x3, 0x2, 0x1a, 0x5, 0x0, 0x4, 0x14)

sha1_header = ''.join(map(chr, sha1_header_tuple))

def sha1_hash_and_encode(message):
     return sha1_header +

def encode_block_from_message(message, intended_length):
     """Algorithm EMSA_PKCS1-v1_5 from PKCS 1 version 2
        intended_length should be one octet less that modulus length
     der_encoding = sha1_hash_and_encode(message)
     assert intended_length >= len(der_encoding) + 10
     pad_string = chr(0xFF) * (intended_length - len(der_encoding) - 2)
     result = chr(1) + pad_string + chr(0) + der_encoding
     return result


More information about the Python-list mailing list