Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions pkcs1/emsa_pkcs1_v15.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,22 @@
hashlib.sha512: b'\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40',
}

def encode(message, em_len, ps=None, hash_class=hashlib.sha1):
DIGEST_INFO_PREFIXES_IMP = {
hashlib.md5: b'\x30\x1e\x30\x0a\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x04\x10',
hashlib.sha1: b'\x30\x1f\x30\x07\x06\x05\x2b\x0e\x03\x02\x1a\x04\x14',
hashlib.sha256: b'\x30\x2f\x30\x0b\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x04\x20',
hashlib.sha384: b'\x30\x3f\x30\x0b\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x04\x30',
hashlib.sha512: b'\x30\x4f\x30\x0b\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x04\x40',
}

def encode(message, em_len, ps=None, hash_class=hashlib.sha1, explicit_null_param=True):
halgo = hash_class(message)
h = halgo.digest()
try:
t = DIGEST_INFO_PREFIXES[hash_class] + h
if explicit_null_param:
t = DIGEST_INFO_PREFIXES[hash_class] + h
else:
t = DIGEST_INFO_PREFIXES_IMP[hash_class] + h
except KeyError:
raise NotImplementedError('hash algorithm is unsupported', hash_class)
if em_len < len(t) + 11:
Expand Down
4 changes: 3 additions & 1 deletion pkcs1/rsassa_pkcs1_v15.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ def verify(public_key, message, signature, hash_class=hashlib.sha1):
try:
em_prime = emsa_pkcs1_v15.encode(message, public_key.byte_size,
hash_class=hash_class)
em_prime_imp = emsa_pkcs1_v15.encode(message, public_key.byte_size,
hash_class=hash_class, explicit_null_param=False)
except ValueError:
raise exceptions.RSAModulusTooShort
return primitives.constant_time_cmp(em, em_prime)
return primitives.constant_time_cmp(em, em_prime) or primitives.constant_time_cmp(em, em_prime_imp)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this still constant time?

In an or statement, Python only evaluates the second condition if the first condition evaluates to True. See the Python specification for Boolean operations..

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right. But don't expect this lib to give you real constant time even with this change. It's a toy implementation, if you need a really hardened implementation of RSA, there are a lot around written in C or ASM.