summaryrefslogtreecommitdiff
path: root/rsa/pkcs1.py
diff options
context:
space:
mode:
authorSybren A. Stüvel <sybren@stuvel.eu>2016-01-22 11:36:06 +0100
committerSybren A. Stüvel <sybren@stuvel.eu>2016-01-22 11:36:06 +0100
commitd3d10345b47c2b17922bb91059cfceea82f82338 (patch)
tree6a336d74ee41a4ba98b6b3d97f123cd0c5f4e9b7 /rsa/pkcs1.py
parent541ee468b6b33c7ae27818bbfea63df9622f9d8a (diff)
downloadrsa-git-d3d10345b47c2b17922bb91059cfceea82f82338.tar.gz
Big refactor to become more PEP8 compliant.
Mostly focused on docstrings (''' → """), indentation, empty lines, and superfluous parenthesis.
Diffstat (limited to 'rsa/pkcs1.py')
-rw-r--r--rsa/pkcs1.py169
1 files changed, 87 insertions, 82 deletions
diff --git a/rsa/pkcs1.py b/rsa/pkcs1.py
index 0e51928..18a80c9 100644
--- a/rsa/pkcs1.py
+++ b/rsa/pkcs1.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Functions for PKCS#1 version 1.5 encryption and signing
+"""Functions for PKCS#1 version 1.5 encryption and signing
This module implements certain functionality from PKCS#1 version 1.5. For a
very clear example, read http://www.di-mgt.com.au/rsa_alg.html#pkcs1schemes
@@ -26,7 +26,7 @@ WARNING: this module leaks information when decryption fails. The exceptions
that are raised contain the Python traceback information, which can be used to
deduce where in the process the failure occurred. DO NOT PASS SUCH INFORMATION
to your users.
-'''
+"""
import hashlib
import os
@@ -51,20 +51,24 @@ HASH_METHODS = {
'SHA-512': hashlib.sha512,
}
+
class CryptoError(Exception):
- '''Base class for all exceptions in this module.'''
+ """Base class for all exceptions in this module."""
+
class DecryptionError(CryptoError):
- '''Raised when decryption fails.'''
+ """Raised when decryption fails."""
+
class VerificationError(CryptoError):
- '''Raised when verification fails.'''
-
+ """Raised when verification fails."""
+
+
def _pad_for_encryption(message, target_length):
- r'''Pads the message for encryption, returning the padded message.
-
+ """Pads the message for encryption, returning the padded message.
+
:return: 00 02 RANDOM_DATA 00 MESSAGE
-
+
>>> block = _pad_for_encryption('hello', 16)
>>> len(block)
16
@@ -73,46 +77,46 @@ def _pad_for_encryption(message, target_length):
>>> block[-6:]
'\x00hello'
- '''
+ """
max_msglength = target_length - 11
msglength = len(message)
-
+
if msglength > max_msglength:
raise OverflowError('%i bytes needed for message, but there is only'
- ' space for %i' % (msglength, max_msglength))
-
+ ' space for %i' % (msglength, max_msglength))
+
# Get random padding
padding = b('')
padding_length = target_length - msglength - 3
-
+
# We remove 0-bytes, so we'll end up with less padding than we've asked for,
# so keep adding data until we're at the correct length.
while len(padding) < padding_length:
needed_bytes = padding_length - len(padding)
-
+
# Always read at least 8 bytes more than we need, and trim off the rest
# after removing the 0-bytes. This increases the chance of getting
# enough bytes, especially when needed_bytes is small
new_padding = os.urandom(needed_bytes + 5)
new_padding = new_padding.replace(b('\x00'), b(''))
padding = padding + new_padding[:needed_bytes]
-
+
assert len(padding) == padding_length
-
+
return b('').join([b('\x00\x02'),
- padding,
- b('\x00'),
- message])
-
+ padding,
+ b('\x00'),
+ message])
+
def _pad_for_signing(message, target_length):
- r'''Pads the message for signing, returning the padded message.
-
+ """Pads the message for signing, returning the padded message.
+
The padding is always a repetition of FF bytes.
-
+
:return: 00 01 PADDING 00 MESSAGE
-
+
>>> block = _pad_for_signing('hello', 16)
>>> len(block)
16
@@ -122,62 +126,63 @@ def _pad_for_signing(message, target_length):
'\x00hello'
>>> block[2:-6]
'\xff\xff\xff\xff\xff\xff\xff\xff'
-
- '''
+
+ """
max_msglength = target_length - 11
msglength = len(message)
-
+
if msglength > max_msglength:
raise OverflowError('%i bytes needed for message, but there is only'
- ' space for %i' % (msglength, max_msglength))
-
+ ' space for %i' % (msglength, max_msglength))
+
padding_length = target_length - msglength - 3
-
+
return b('').join([b('\x00\x01'),
- padding_length * b('\xff'),
- b('\x00'),
- message])
-
-
+ padding_length * b('\xff'),
+ b('\x00'),
+ message])
+
+
def encrypt(message, pub_key):
- '''Encrypts the given message using PKCS#1 v1.5
-
+ """Encrypts the given message using PKCS#1 v1.5
+
:param message: the message to encrypt. Must be a byte string no longer than
``k-11`` bytes, where ``k`` is the number of bytes needed to encode
the ``n`` component of the public key.
:param pub_key: the :py:class:`rsa.PublicKey` to encrypt with.
:raise OverflowError: when the message is too large to fit in the padded
block.
-
+
>>> from rsa import key, common
>>> (pub_key, priv_key) = key.newkeys(256)
>>> message = 'hello'
>>> crypto = encrypt(message, pub_key)
-
+
The crypto text should be just as long as the public key 'n' component:
>>> len(crypto) == common.byte_size(pub_key.n)
True
-
- '''
-
+
+ """
+
keylength = common.byte_size(pub_key.n)
padded = _pad_for_encryption(message, keylength)
-
+
payload = transform.bytes2int(padded)
encrypted = core.encrypt_int(payload, pub_key.e, pub_key.n)
block = transform.int2bytes(encrypted, keylength)
-
+
return block
+
def decrypt(crypto, priv_key):
- r'''Decrypts the given message using PKCS#1 v1.5
-
+ """Decrypts the given message using PKCS#1 v1.5
+
The decryption is considered 'failed' when the resulting cleartext doesn't
start with the bytes 00 02, or when the 00 byte between the padding and
the message cannot be found.
-
+
:param crypto: the crypto text as returned by :py:func:`rsa.encrypt`
:param priv_key: the :py:class:`rsa.PrivateKey` to decrypt with.
:raise DecryptionError: when the decryption fails. No details are given as
@@ -193,7 +198,7 @@ def decrypt(crypto, priv_key):
>>> crypto = encrypt('hello', pub_key)
>>> decrypt(crypto, priv_key)
'hello'
-
+
And with binary data:
>>> crypto = encrypt('\x00\x00\x00\x00\x01', pub_key)
@@ -220,8 +225,8 @@ def decrypt(crypto, priv_key):
...
DecryptionError: Decryption failed
- '''
-
+ """
+
blocksize = common.byte_size(priv_key.n)
encrypted = transform.bytes2int(crypto)
decrypted = core.decrypt_int(encrypted, priv_key.d, priv_key.n)
@@ -230,21 +235,22 @@ def decrypt(crypto, priv_key):
# If we can't find the cleartext marker, decryption failed.
if cleartext[0:2] != b('\x00\x02'):
raise DecryptionError('Decryption failed')
-
+
# Find the 00 separator between the padding and the message
try:
sep_idx = cleartext.index(b('\x00'), 2)
except ValueError:
raise DecryptionError('Decryption failed')
-
- return cleartext[sep_idx+1:]
-
+
+ return cleartext[sep_idx + 1:]
+
+
def sign(message, priv_key, hash):
- '''Signs the message with the private key.
+ """Signs the message with the private key.
Hashes the message, then signs the hash with the given key. This is known
as a "detached signature", because the message itself isn't altered.
-
+
:param message: the message to sign. Can be an 8-bit string or a file-like
object. If ``message`` has a ``read()`` method, it is assumed to be a
file-like object.
@@ -255,13 +261,13 @@ def sign(message, priv_key, hash):
:raise OverflowError: if the private key is too small to contain the
requested hash.
- '''
+ """
# Get the ASN1 code for this hash method
if hash not in HASH_ASN1:
raise ValueError('Invalid hash method: %s' % hash)
asn1code = HASH_ASN1[hash]
-
+
# Calculate the hash
hash = _hash(message, hash)
@@ -269,18 +275,19 @@ def sign(message, priv_key, hash):
cleartext = asn1code + hash
keylength = common.byte_size(priv_key.n)
padded = _pad_for_signing(cleartext, keylength)
-
+
payload = transform.bytes2int(padded)
encrypted = core.encrypt_int(payload, priv_key.d, priv_key.n)
block = transform.int2bytes(encrypted, keylength)
-
+
return block
+
def verify(message, signature, pub_key):
- '''Verifies that the signature matches the message.
-
+ """Verifies that the signature matches the message.
+
The hash method is detected automatically from the signature.
-
+
:param message: the signed message. Can be an 8-bit string or a file-like
object. If ``message`` has a ``read()`` method, it is assumed to be a
file-like object.
@@ -288,13 +295,13 @@ def verify(message, signature, pub_key):
:param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message.
:raise VerificationError: when the signature doesn't match the message.
- '''
-
+ """
+
keylength = common.byte_size(pub_key.n)
encrypted = transform.bytes2int(signature)
decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
clearsig = transform.int2bytes(decrypted, keylength)
-
+
# Get the hash method
method_name = _find_method_hash(clearsig)
message_hash = _hash(message, method_name)
@@ -309,20 +316,21 @@ def verify(message, signature, pub_key):
return True
+
def _hash(message, method_name):
- '''Returns the message digest.
-
+ """Returns the message digest.
+
:param message: the signed message. Can be an 8-bit string or a file-like
object. If ``message`` has a ``read()`` method, it is assumed to be a
file-like object.
:param method_name: the hash method, must be a key of
:py:const:`HASH_METHODS`.
-
- '''
+
+ """
if method_name not in HASH_METHODS:
raise ValueError('Invalid hash method: %s' % method_name)
-
+
method = HASH_METHODS[method_name]
hasher = method()
@@ -338,20 +346,17 @@ def _hash(message, method_name):
def _find_method_hash(clearsig):
- '''Finds the hash method.
-
+ """Finds the hash method.
+
:param clearsig: full padded ASN1 and hash.
-
:return: the used hash method.
-
:raise VerificationFailed: when the hash method cannot be found
-
- '''
+ """
for (hashname, asn1code) in HASH_ASN1.items():
if asn1code in clearsig:
return hashname
-
+
raise VerificationError('Verification failed')
@@ -361,13 +366,13 @@ __all__ = ['encrypt', 'decrypt', 'sign', 'verify',
if __name__ == '__main__':
print('Running doctests 1000x or until failure')
import doctest
-
+
for count in range(1000):
(failures, tests) = doctest.testmod()
if failures:
break
-
+
if count and count % 100 == 0:
print('%i times' % count)
-
+
print('Doctests done')