summaryrefslogtreecommitdiff
path: root/rsa
diff options
context:
space:
mode:
authorYesudeep Mangalapilly <yesudeep@gmail.com>2011-08-16 14:30:48 +0530
committerYesudeep Mangalapilly <yesudeep@gmail.com>2011-08-16 14:30:48 +0530
commit74f1e76d61d7a066653184273b87dea4ce6f1502 (patch)
tree828db6ba67a52aab6323981fbd7d0bfa5074e605 /rsa
parent7790c1a15383b8b82ed2746fe0b54c554c430829 (diff)
downloadrsa-74f1e76d61d7a066653184273b87dea4ce6f1502.tar.gz
Parellelized testing. Caught a lot of bugs.
Diffstat (limited to 'rsa')
-rw-r--r--rsa/_compat.py7
-rw-r--r--rsa/bigfile.py12
-rw-r--r--rsa/cli.py60
-rw-r--r--rsa/common.py43
-rw-r--r--rsa/core.py4
-rw-r--r--rsa/key.py62
-rw-r--r--rsa/parallel.py4
-rw-r--r--rsa/pem.py14
-rw-r--r--rsa/pkcs1.py42
-rw-r--r--rsa/prime.py4
-rw-r--r--rsa/randnum.py6
-rw-r--r--rsa/transform.py20
-rw-r--r--rsa/util.py6
-rw-r--r--rsa/varblock.py20
14 files changed, 133 insertions, 171 deletions
diff --git a/rsa/_compat.py b/rsa/_compat.py
index 39a967b..7533c36 100644
--- a/rsa/_compat.py
+++ b/rsa/_compat.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Python compatibility wrappers.'''
+"""Python compatibility wrappers."""
from __future__ import absolute_import
@@ -108,11 +108,6 @@ def byte(num):
Use it as a replacement for ``chr`` where you are expecting a byte
because this will work on all current versions of Python::
- >>> byte(0)
- '\x00'
- >>> byte(255)
- '\xff'
-
:param num:
An unsigned integer between 0 and 255 (both inclusive).
:returns:
diff --git a/rsa/bigfile.py b/rsa/bigfile.py
index 26063f1..ed3fdb9 100644
--- a/rsa/bigfile.py
+++ b/rsa/bigfile.py
@@ -13,7 +13,7 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Large file support
+"""Large file support
- break a file into smaller blocks, and encrypt them, and store the
encrypted blocks in another file.
@@ -36,19 +36,19 @@ The encrypted file format is as follows, where || denotes byte concatenation:
This file format is called the VARBLOCK format, in line with the varint format
used to denote the block sizes.
-'''
+"""
from rsa import key, common, pkcs1, varblock
from rsa._compat import byte
def encrypt_bigfile(infile, outfile, pub_key):
- '''Encrypts a file, writing it to 'outfile' in VARBLOCK format.
+ """Encrypts a file, writing it to 'outfile' in VARBLOCK format.
:param infile: file-like object to read the cleartext from
:param outfile: file-like object to write the crypto in VARBLOCK format to
:param pub_key: :py:class:`rsa.PublicKey` to encrypt with
- '''
+ """
if not isinstance(pub_key, key.PublicKey):
raise TypeError('Public key required, but got %r' % pub_key)
@@ -67,13 +67,13 @@ def encrypt_bigfile(infile, outfile, pub_key):
outfile.write(crypto)
def decrypt_bigfile(infile, outfile, priv_key):
- '''Decrypts an encrypted VARBLOCK file, writing it to 'outfile'
+ """Decrypts an encrypted VARBLOCK file, writing it to 'outfile'
:param infile: file-like object to read the crypto in VARBLOCK format from
:param outfile: file-like object to write the cleartext to
:param priv_key: :py:class:`rsa.PrivateKey` to decrypt with
- '''
+ """
if not isinstance(priv_key, key.PrivateKey):
raise TypeError('Private key required, but got %r' % priv_key)
diff --git a/rsa/cli.py b/rsa/cli.py
index 012c77d..382a915 100644
--- a/rsa/cli.py
+++ b/rsa/cli.py
@@ -14,10 +14,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Commandline scripts.
+"""Commandline scripts.
These scripts are called by the executables defined in setup.py.
-'''
+"""
+
+from __future__ import with_statement
import abc
import sys
@@ -30,7 +32,7 @@ import rsa.pkcs1
HASH_METHODS = sorted(rsa.pkcs1.HASH_METHODS.keys())
def keygen():
- '''Key generator.'''
+ """Key generator."""
# Parse the CLI options
parser = OptionParser(usage='usage: %prog [options] keysize',
@@ -86,7 +88,7 @@ def keygen():
class CryptoOperation(object):
- '''CLI callable that operates with input, output, and a key.'''
+ """CLI callable that operates with input, output, and a key."""
__metaclass__ = abc.ABCMeta
@@ -112,15 +114,15 @@ class CryptoOperation(object):
@abc.abstractmethod
def perform_operation(self, indata, key, cli_args=None):
- '''Performs the program's operation.
+ """Performs the program's operation.
Implement in a subclass.
:returns: the data to write to the output.
- '''
+ """
def __call__(self):
- '''Runs the program.'''
+ """Runs the program."""
(cli, cli_args) = self.parse_cli()
@@ -135,10 +137,10 @@ class CryptoOperation(object):
self.write_outfile(outdata, cli.output)
def parse_cli(self):
- '''Parse the CLI options
+ """Parse the CLI options
:returns: (cli_opts, cli_args)
- '''
+ """
parser = OptionParser(usage=self.usage, description=self.description)
@@ -160,7 +162,7 @@ class CryptoOperation(object):
return (cli, cli_args)
def read_key(self, filename, keyform):
- '''Reads a public or private key.'''
+ """Reads a public or private key."""
print >>sys.stderr, 'Reading %s key from %s' % (self.keyname, filename)
with open(filename) as keyfile:
@@ -169,7 +171,7 @@ class CryptoOperation(object):
return self.key_class.load_pkcs1(keydata, keyform)
def read_infile(self, inname):
- '''Read the input file'''
+ """Read the input file"""
if inname:
print >>sys.stderr, 'Reading input from %s' % inname
@@ -180,7 +182,7 @@ class CryptoOperation(object):
return sys.stdin.read()
def write_outfile(self, outdata, outname):
- '''Write the output file'''
+ """Write the output file"""
if outname:
print >>sys.stderr, 'Writing output to %s' % outname
@@ -191,7 +193,7 @@ class CryptoOperation(object):
sys.stdout.write(outdata)
class EncryptOperation(CryptoOperation):
- '''Encrypts a file.'''
+ """Encrypts a file."""
keyname = 'public'
description = ('Encrypts a file. The file must be shorter than the key '
@@ -203,12 +205,12 @@ class EncryptOperation(CryptoOperation):
def perform_operation(self, indata, pub_key, cli_args=None):
- '''Encrypts files.'''
+ """Encrypts files."""
return rsa.encrypt(indata, pub_key)
class DecryptOperation(CryptoOperation):
- '''Decrypts a file.'''
+ """Decrypts a file."""
keyname = 'private'
description = ('Decrypts a file. The original file must be shorter than '
@@ -220,12 +222,12 @@ class DecryptOperation(CryptoOperation):
key_class = rsa.PrivateKey
def perform_operation(self, indata, priv_key, cli_args=None):
- '''Decrypts files.'''
+ """Decrypts files."""
return rsa.decrypt(indata, priv_key)
class SignOperation(CryptoOperation):
- '''Signs a file.'''
+ """Signs a file."""
keyname = 'private'
usage = 'usage: %%prog [options] private_key hash_method'
@@ -241,7 +243,7 @@ class SignOperation(CryptoOperation):
'to stdout if this option is not present.')
def perform_operation(self, indata, priv_key, cli_args):
- '''Decrypts files.'''
+ """Decrypts files."""
hash_method = cli_args[1]
if hash_method not in HASH_METHODS:
@@ -251,7 +253,7 @@ class SignOperation(CryptoOperation):
return rsa.sign(indata, priv_key, hash_method)
class VerifyOperation(CryptoOperation):
- '''Verify a signature.'''
+ """Verify a signature."""
keyname = 'public'
usage = 'usage: %%prog [options] private_key signature_file'
@@ -265,7 +267,7 @@ class VerifyOperation(CryptoOperation):
has_output = False
def perform_operation(self, indata, pub_key, cli_args):
- '''Decrypts files.'''
+ """Decrypts files."""
signature_file = cli_args[1]
@@ -281,7 +283,7 @@ class VerifyOperation(CryptoOperation):
class BigfileOperation(CryptoOperation):
- '''CryptoOperation that doesn't read the entire file into memory.'''
+ """CryptoOperation that doesn't read the entire file into memory."""
def __init__(self):
CryptoOperation.__init__(self)
@@ -289,13 +291,13 @@ class BigfileOperation(CryptoOperation):
self.file_objects = []
def __del__(self):
- '''Closes any open file handles.'''
+ """Closes any open file handles."""
for fobj in self.file_objects:
fobj.close()
def __call__(self):
- '''Runs the program.'''
+ """Runs the program."""
(cli, cli_args) = self.parse_cli()
@@ -310,7 +312,7 @@ class BigfileOperation(CryptoOperation):
self.perform_operation(infile, outfile, key, cli_args)
def get_infile(self, inname):
- '''Returns the input file object'''
+ """Returns the input file object"""
if inname:
print >>sys.stderr, 'Reading input from %s' % inname
@@ -323,7 +325,7 @@ class BigfileOperation(CryptoOperation):
return fobj
def get_outfile(self, outname):
- '''Returns the output file object'''
+ """Returns the output file object"""
if outname:
print >>sys.stderr, 'Will write output to %s' % outname
@@ -336,7 +338,7 @@ class BigfileOperation(CryptoOperation):
return fobj
class EncryptBigfileOperation(BigfileOperation):
- '''Encrypts a file to VARBLOCK format.'''
+ """Encrypts a file to VARBLOCK format."""
keyname = 'public'
description = ('Encrypts a file to an encrypted VARBLOCK file. The file '
@@ -347,12 +349,12 @@ class EncryptBigfileOperation(BigfileOperation):
operation_progressive = 'encrypting'
def perform_operation(self, infile, outfile, pub_key, cli_args=None):
- '''Encrypts files to VARBLOCK.'''
+ """Encrypts files to VARBLOCK."""
return rsa.bigfile.encrypt_bigfile(infile, outfile, pub_key)
class DecryptBigfileOperation(BigfileOperation):
- '''Decrypts a file in VARBLOCK format.'''
+ """Decrypts a file in VARBLOCK format."""
keyname = 'private'
description = ('Decrypts an encrypted VARBLOCK file that was encrypted '
@@ -363,7 +365,7 @@ class DecryptBigfileOperation(BigfileOperation):
key_class = rsa.PrivateKey
def perform_operation(self, infile, outfile, priv_key, cli_args=None):
- '''Decrypts a VARBLOCK file.'''
+ """Decrypts a VARBLOCK file."""
return rsa.bigfile.decrypt_bigfile(infile, outfile, priv_key)
diff --git a/rsa/common.py b/rsa/common.py
index 11e52ec..5730ac3 100644
--- a/rsa/common.py
+++ b/rsa/common.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Common functionality shared by several modules.'''
+"""Common functionality shared by several modules."""
def bit_size(num):
@@ -61,29 +61,14 @@ def bit_size(num):
def _bit_size(number):
- '''Returns the number of bits required to hold a specific long number.
-
- >>> bit_size(1023)
- 10
- >>> bit_size(1024)
- 11
- >>> bit_size(1025)
- 11
-
- >>> bit_size(1 << 1024)
- 1025
- >>> bit_size((1 << 1024) + 1)
- 1025
- >>> bit_size((1 << 1024) - 1)
- 1024
-
- '''
-
+ """
+ Returns the number of bits required to hold a specific long number.
+ """
if number < 0:
raise ValueError('Only nonnegative numbers possible: %s' % number)
if number == 0:
- return 1
+ return 0
# This works, even with very large numbers. When using math.log(number, 2),
# you'll get rounding errors and it'll fail.
@@ -99,15 +84,9 @@ def byte_size(number):
"""Returns the number of bytes required to hold a specific long number.
The number of bytes is rounded up.
-
- >>> byte_size(1 << 1023)
- 128
- >>> byte_size((1 << 1024) - 1)
- 128
- >>> byte_size(1 << 1024)
- 129
"""
-
+ if number == 0:
+ return 0
# Does not perform floating-point division and uses built-in divmod
# operator.
quanta, mod = divmod(bit_size(number), 8)
@@ -140,13 +119,13 @@ def extended_gcd(a, b):
return (a, lx, ly) #Return only positive values
def inverse(x, n):
- '''Returns x^-1 (mod n)
+ """Returns x^-1 (mod n)
>>> inverse(7, 4)
3
>>> (inverse(143, 4) * 143) % 4
1
- '''
+ """
(divider, inv, _) = extended_gcd(x, n)
@@ -157,7 +136,7 @@ def inverse(x, n):
def crt(a_values, modulo_values):
- '''Chinese Remainder Theorem.
+ """Chinese Remainder Theorem.
Calculates x such that x = a[i] (mod m[i]) for each i.
@@ -174,7 +153,7 @@ def crt(a_values, modulo_values):
>>> crt([2, 3, 0], [7, 11, 15])
135
- '''
+ """
m = 1
x = 0
diff --git a/rsa/core.py b/rsa/core.py
index fbc108a..27d829e 100644
--- a/rsa/core.py
+++ b/rsa/core.py
@@ -13,11 +13,11 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Core mathematical operations.
+"""Core mathematical operations.
This is the actual core RSA implementation, which is only defined
mathematically on integers.
-'''
+"""
from rsa._compat import is_integer
diff --git a/rsa/key.py b/rsa/key.py
index facde8e..dc4465d 100644
--- a/rsa/key.py
+++ b/rsa/key.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''RSA key generation code.
+"""RSA key generation code.
Create new keys with the newkeys() function. It will give you a PublicKey and a
PrivateKey object.
@@ -23,7 +23,7 @@ Loading and saving keys requires the pyasn1 module. This module is imported as
late as possible, such that other functionality will remain working in absence
of pyasn1.
-'''
+"""
import logging
from rsa._compat import b
@@ -35,11 +35,11 @@ import rsa.common
log = logging.getLogger(__name__)
class AbstractKey(object):
- '''Abstract superclass for private and public keys.'''
+ """Abstract superclass for private and public keys."""
@classmethod
def load_pkcs1(cls, keyfile, format='PEM'):
- r'''Loads a key in PKCS#1 DER or PEM format.
+ r"""Loads a key in PKCS#1 DER or PEM format.
:param keyfile: contents of a DER- or PEM-encoded file that contains
the public key.
@@ -47,7 +47,7 @@ class AbstractKey(object):
:return: a PublicKey object
- '''
+ """
methods = {
'PEM': cls._load_pkcs1_pem,
@@ -63,12 +63,12 @@ class AbstractKey(object):
return method(keyfile)
def save_pkcs1(self, format='PEM'):
- '''Saves the public key in PKCS#1 DER or PEM format.
+ """Saves the public key in PKCS#1 DER or PEM format.
:param format: the format to save; 'PEM' or 'DER'
:returns: the DER- or PEM-encoded public key.
- '''
+ """
methods = {
'PEM': self._save_pkcs1_pem,
@@ -84,7 +84,7 @@ class AbstractKey(object):
return method()
class PublicKey(AbstractKey):
- '''Represents a public RSA key.
+ """Represents a public RSA key.
This key is also known as the 'encryption key'. It contains the 'n' and 'e'
values.
@@ -105,7 +105,7 @@ class PublicKey(AbstractKey):
>>> key['e']
3
- '''
+ """
__slots__ = ('n', 'e')
@@ -133,7 +133,7 @@ class PublicKey(AbstractKey):
@classmethod
def _load_pkcs1_der(cls, keyfile):
- r'''Loads a key in PKCS#1 DER format.
+ r"""Loads a key in PKCS#1 DER format.
@param keyfile: contents of a DER-encoded file that contains the public
key.
@@ -150,7 +150,7 @@ class PublicKey(AbstractKey):
>>> PublicKey._load_pkcs1_der(der)
PublicKey(2367317549, 65537)
- '''
+ """
from pyasn1.codec.der import decoder
(priv, _) = decoder.decode(keyfile)
@@ -165,10 +165,10 @@ class PublicKey(AbstractKey):
return cls(*as_ints)
def _save_pkcs1_der(self):
- '''Saves the public key in PKCS#1 DER format.
+ """Saves the public key in PKCS#1 DER format.
@returns: the DER-encoded public key.
- '''
+ """
from pyasn1.type import univ, namedtype
from pyasn1.codec.der import encoder
@@ -188,7 +188,7 @@ class PublicKey(AbstractKey):
@classmethod
def _load_pkcs1_pem(cls, keyfile):
- '''Loads a PKCS#1 PEM-encoded public key file.
+ """Loads a PKCS#1 PEM-encoded public key file.
The contents of the file before the "-----BEGIN RSA PUBLIC KEY-----" and
after the "-----END RSA PUBLIC KEY-----" lines is ignored.
@@ -196,22 +196,22 @@ class PublicKey(AbstractKey):
@param keyfile: contents of a PEM-encoded file that contains the public
key.
@return: a PublicKey object
- '''
+ """
der = rsa.pem.load_pem(keyfile, 'RSA PUBLIC KEY')
return cls._load_pkcs1_der(der)
def _save_pkcs1_pem(self):
- '''Saves a PKCS#1 PEM-encoded public key file.
+ """Saves a PKCS#1 PEM-encoded public key file.
@return: contents of a PEM-encoded file that contains the public key.
- '''
+ """
der = self._save_pkcs1_der()
return rsa.pem.save_pem(der, 'RSA PUBLIC KEY')
class PrivateKey(AbstractKey):
- '''Represents a private RSA key.
+ """Represents a private RSA key.
This key is also known as the 'decryption key'. It contains the 'n', 'e',
'd', 'p', 'q' and other values.
@@ -242,7 +242,7 @@ class PrivateKey(AbstractKey):
>>> pk.coef
8
- '''
+ """
__slots__ = ('n', 'e', 'd', 'p', 'q', 'exp1', 'exp2', 'coef')
@@ -296,7 +296,7 @@ class PrivateKey(AbstractKey):
@classmethod
def _load_pkcs1_der(cls, keyfile):
- r'''Loads a key in PKCS#1 DER format.
+ r"""Loads a key in PKCS#1 DER format.
@param keyfile: contents of a DER-encoded file that contains the private
key.
@@ -313,7 +313,7 @@ class PrivateKey(AbstractKey):
>>> PrivateKey._load_pkcs1_der(der)
PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
- '''
+ """
from pyasn1.codec.der import decoder
(priv, _) = decoder.decode(keyfile)
@@ -340,10 +340,10 @@ class PrivateKey(AbstractKey):
return cls(*as_ints)
def _save_pkcs1_der(self):
- '''Saves the private key in PKCS#1 DER format.
+ """Saves the private key in PKCS#1 DER format.
@returns: the DER-encoded private key.
- '''
+ """
from pyasn1.type import univ, namedtype
from pyasn1.codec.der import encoder
@@ -377,7 +377,7 @@ class PrivateKey(AbstractKey):
@classmethod
def _load_pkcs1_pem(cls, keyfile):
- '''Loads a PKCS#1 PEM-encoded private key file.
+ """Loads a PKCS#1 PEM-encoded private key file.
The contents of the file before the "-----BEGIN RSA PRIVATE KEY-----" and
after the "-----END RSA PRIVATE KEY-----" lines is ignored.
@@ -385,22 +385,22 @@ class PrivateKey(AbstractKey):
@param keyfile: contents of a PEM-encoded file that contains the private
key.
@return: a PrivateKey object
- '''
+ """
der = rsa.pem.load_pem(keyfile, b('RSA PRIVATE KEY'))
return cls._load_pkcs1_der(der)
def _save_pkcs1_pem(self):
- '''Saves a PKCS#1 PEM-encoded private key file.
+ """Saves a PKCS#1 PEM-encoded private key file.
@return: contents of a PEM-encoded file that contains the private key.
- '''
+ """
der = self._save_pkcs1_der()
return rsa.pem.save_pem(der, b('RSA PRIVATE KEY'))
def find_p_q(nbits, getprime_func=rsa.prime.getprime, accurate=True):
- ''''Returns a tuple of two different primes of nbits bits each.
+ """'Returns a tuple of two different primes of nbits bits each.
The resulting p * q has exacty 2 * nbits bits, and the returned p and q
will not be equal.
@@ -428,7 +428,7 @@ def find_p_q(nbits, getprime_func=rsa.prime.getprime, accurate=True):
>>> common.bit_size(p * q) > 240
True
- '''
+ """
total_bits = nbits * 2
@@ -445,11 +445,11 @@ def find_p_q(nbits, getprime_func=rsa.prime.getprime, accurate=True):
q = getprime_func(qbits)
def is_acceptable(p, q):
- '''Returns True iff p and q are acceptable:
+ """Returns True iff p and q are acceptable:
- p and q differ
- (p * q) has the right nr of bits (when accurate=True)
- '''
+ """
if p == q:
return False
diff --git a/rsa/parallel.py b/rsa/parallel.py
index 82042c8..8c03f79 100644
--- a/rsa/parallel.py
+++ b/rsa/parallel.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Functions for parallel computation on multiple cores.
+"""Functions for parallel computation on multiple cores.
Introduced in Python-RSA 3.1.
@@ -22,7 +22,7 @@ Introduced in Python-RSA 3.1.
Requires Python 2.6 or newer.
-'''
+"""
import multiprocessing as mp
diff --git a/rsa/pem.py b/rsa/pem.py
index 0875ec3..b632ceb 100644
--- a/rsa/pem.py
+++ b/rsa/pem.py
@@ -14,18 +14,18 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Functions that load and write PEM-encoded files.'''
+"""Functions that load and write PEM-encoded files."""
import base64
from rsa._compat import b, is_bytes
def _markers(pem_marker):
- '''Returns the start and end PEM markers
+ """Returns the start and end PEM markers
>>> _markers('RSA PRIVATE KEY')
('-----BEGIN RSA PRIVATE KEY-----', '-----END RSA PRIVATE KEY-----')
- '''
+ """
if is_bytes(pem_marker):
pem_marker = pem_marker.decode('utf-8')
@@ -34,7 +34,7 @@ def _markers(pem_marker):
b('-----END %s-----' % pem_marker))
def load_pem(contents, pem_marker):
- '''Loads a PEM file.
+ """Loads a PEM file.
@param contents: the contents of the file to interpret
@param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
@@ -46,7 +46,7 @@ def load_pem(contents, pem_marker):
@raise ValueError: when the content is invalid, for example when the start
marker cannot be found.
- '''
+ """
(pem_start, pem_end) = _markers(pem_marker)
@@ -96,7 +96,7 @@ def load_pem(contents, pem_marker):
def save_pem(contents, pem_marker):
- '''Saves a PEM file.
+ """Saves a PEM file.
@param contents: the contents to encode in PEM format
@param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
@@ -105,7 +105,7 @@ def save_pem(contents, pem_marker):
@return the base64-encoded content between the start and end markers.
- '''
+ """
(pem_start, pem_end) = _markers(pem_marker)
diff --git a/rsa/pkcs1.py b/rsa/pkcs1.py
index 8c6d290..4c92111 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 or verification 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
@@ -52,16 +52,16 @@ HASH_METHODS = {
}
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.
+ r"""Pads the message for encryption, returning the padded message.
:return: 00 02 RANDOM_DATA 00 MESSAGE
@@ -73,7 +73,7 @@ def _pad_for_encryption(message, target_length):
>>> block[-6:]
'\x00hello'
- '''
+ """
max_msglength = target_length - 11
msglength = len(message)
@@ -107,7 +107,7 @@ def _pad_for_encryption(message, target_length):
def _pad_for_signing(message, target_length):
- r'''Pads the message for signing, returning the padded message.
+ r"""Pads the message for signing, returning the padded message.
The padding is always a repetition of FF bytes.
@@ -123,7 +123,7 @@ def _pad_for_signing(message, target_length):
>>> block[2:-6]
'\xff\xff\xff\xff\xff\xff\xff\xff'
- '''
+ """
max_msglength = target_length - 11
msglength = len(message)
@@ -141,7 +141,7 @@ def _pad_for_signing(message, target_length):
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
@@ -160,7 +160,7 @@ def encrypt(message, pub_key):
>>> len(crypto) == common.byte_size(pub_key.n)
True
- '''
+ """
keylength = common.byte_size(pub_key.n)
padded = _pad_for_encryption(message, keylength)
@@ -172,7 +172,7 @@ def encrypt(message, pub_key):
return block
def decrypt(crypto, priv_key):
- r'''Decrypts the given message using PKCS#1 v1.5
+ r"""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
@@ -220,7 +220,7 @@ def decrypt(crypto, priv_key):
...
DecryptionError: Decryption failed
- '''
+ """
blocksize = common.byte_size(priv_key.n)
encrypted = transform.bytes2int(crypto)
@@ -240,7 +240,7 @@ def decrypt(crypto, priv_key):
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.
@@ -255,7 +255,7 @@ 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:
@@ -277,7 +277,7 @@ def sign(message, priv_key, hash):
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.
@@ -296,7 +296,7 @@ def verify(message, signature, pub_key):
key. It's only a tiny bit of information, but every bit makes cracking
the keys easier.
- '''
+ """
blocksize = common.byte_size(pub_key.n)
encrypted = transform.bytes2int(signature)
@@ -322,7 +322,7 @@ def verify(message, signature, pub_key):
raise VerificationError('Verification failed')
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
@@ -330,7 +330,7 @@ def _hash(message, method_name):
: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)
@@ -350,7 +350,7 @@ def _hash(message, method_name):
def _find_method_hash(method_hash):
- '''Finds the hash method and the hash itself.
+ """Finds the hash method and the hash itself.
:param method_hash: ASN1 code for the hash method concatenated with the
hash itself.
@@ -360,7 +360,7 @@ def _find_method_hash(method_hash):
:raise VerificationFailed: when the hash method cannot be found
- '''
+ """
for (hashname, asn1code) in HASH_ASN1.items():
if not method_hash.startswith(asn1code):
diff --git a/rsa/prime.py b/rsa/prime.py
index 4dc190c..141d3df 100644
--- a/rsa/prime.py
+++ b/rsa/prime.py
@@ -14,11 +14,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Numerical functions related to primes.
+"""Numerical functions related to primes.
Implementation based on the book Algorithm Design by Michael T. Goodrich and
Roberto Tamassia, 2002.
-'''
+"""
__all__ = [ 'getprime', 'are_relatively_prime']
diff --git a/rsa/randnum.py b/rsa/randnum.py
index 275da0f..f6494d8 100644
--- a/rsa/randnum.py
+++ b/rsa/randnum.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Functions for generating random numbers.'''
+"""Functions for generating random numbers."""
# Source inspired by code by Yesudeep Mangalapilly <yesudeep@gmail.com>
@@ -24,11 +24,11 @@ from rsa import common, transform
from rsa._compat import byte
def read_random_bits(nbits):
- '''Reads 'nbits' random bits.
+ """Reads 'nbits' random bits.
If nbits isn't a whole number of bytes, an extra byte will be appended with
only the lower bits set.
- '''
+ """
nbytes, rbits = divmod(nbits, 8)
diff --git a/rsa/transform.py b/rsa/transform.py
index 7dba2e0..9ba2fe7 100644
--- a/rsa/transform.py
+++ b/rsa/transform.py
@@ -14,10 +14,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Data transformation functions.
+"""Data transformation functions.
From bytes to a number, number to bytes, etc.
-'''
+"""
from __future__ import absolute_import
@@ -64,22 +64,6 @@ def _int2bytes(number, block_size=0):
@throws OverflowError when block_size is given and the number takes up more
bytes than fit into the block.
-
- >>> _int2bytes(123456789)
- b'\x07[\xcd\x15'
- >>> bytes2int(int2bytes(123456789))
- 123456789
-
- >>> _int2bytes(123456789, 6)
- b'\x00\x00\x07[\xcd\x15'
- >>> bytes2int(int2bytes(123456789, 128))
- 123456789
-
- >>> _int2bytes(123456789, 3)
- Traceback (most recent call last):
- ...
- OverflowError: Needed 4 bytes for number, but block size is 3
-
"""
# Type checking
if not is_integer(number):
diff --git a/rsa/util.py b/rsa/util.py
index db6944e..b6df049 100644
--- a/rsa/util.py
+++ b/rsa/util.py
@@ -14,7 +14,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Utility functions.'''
+"""Utility functions."""
+
+from __future__ import with_statement
import sys
from optparse import OptionParser
@@ -22,7 +24,7 @@ from optparse import OptionParser
import rsa.key
def private_to_public():
- '''Reads a private key and outputs the corresponding public key.'''
+ """Reads a private key and outputs the corresponding public key."""
# Parse the CLI options
parser = OptionParser(usage='usage: %prog [options]',
diff --git a/rsa/varblock.py b/rsa/varblock.py
index 51e04fc..d5a342b 100644
--- a/rsa/varblock.py
+++ b/rsa/varblock.py
@@ -13,7 +13,7 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-'''VARBLOCK file support
+"""VARBLOCK file support
The VARBLOCK file format is as follows, where || denotes byte concatenation:
@@ -30,13 +30,13 @@ The VARBLOCK file format is as follows, where || denotes byte concatenation:
This file format is called the VARBLOCK format, in line with the varint format
used to denote the block sizes.
-'''
+"""
from rsa._compat import byte
VARBLOCK_VERSION = 1
def read_varint(infile):
- '''Reads a varint from the file.
+ """Reads a varint from the file.
When the first byte to be read indicates EOF, (0, 0) is returned. When an
EOF occurs when at least one byte has been read, an EOFError exception is
@@ -45,7 +45,7 @@ def read_varint(infile):
@param infile: the file-like object to read from. It should have a read()
method.
@returns (varint, length), the read varint and the number of read bytes.
- '''
+ """
varint = 0
read_bytes = 0
@@ -67,12 +67,12 @@ def read_varint(infile):
return (varint, read_bytes)
def write_varint(outfile, value):
- '''Writes a varint to a file.
+ """Writes a varint to a file.
@param outfile: the file-like object to write to. It should have a write()
method.
@returns the number of written bytes.
- '''
+ """
# there is a big difference between 'write the value 0' (this case) and
# 'there is nothing left to write' (the false-case of the while loop)
@@ -96,12 +96,12 @@ def write_varint(outfile, value):
def yield_varblocks(infile):
- '''Generator, yields each block in the input file.
+ """Generator, yields each block in the input file.
@param infile: file to read, is expected to have the VARBLOCK format as
described in the module's docstring.
@yields the contents of each block.
- '''
+ """
# Check the version number
first_char = infile.read(1)
@@ -130,11 +130,11 @@ def yield_varblocks(infile):
yield block
def yield_fixedblocks(infile, blocksize):
- '''Generator, yields each block of ``blocksize`` bytes in the input file.
+ """Generator, yields each block of ``blocksize`` bytes in the input file.
:param infile: file to read and separate in blocks.
:returns: a generator that yields the contents of each block
- '''
+ """
while True:
block = infile.read(blocksize)