summaryrefslogtreecommitdiff
path: root/rsa
diff options
context:
space:
mode:
authorYesudeep Mangalapilly <yesudeep@gmail.com>2011-08-24 16:53:39 +0530
committerYesudeep Mangalapilly <yesudeep@gmail.com>2011-08-24 16:53:39 +0530
commit9d584615f738f6ca7673fc9aa8555d6542fe9fef (patch)
tree0d752cc34ec7b64a4b1f70caabee05b733157cf6 /rsa
parentf4283ae7b366233afa29a8c62a432480cd17b706 (diff)
downloadrsa-9d584615f738f6ca7673fc9aa8555d6542fe9fef.tar.gz
Reverts docstring quoting syntax.
Diffstat (limited to 'rsa')
-rw-r--r--rsa/bigfile.py13
-rw-r--r--rsa/cli.py58
-rw-r--r--rsa/common.py26
-rw-r--r--rsa/core.py11
-rw-r--r--rsa/key.py74
-rw-r--r--rsa/parallel.py8
-rw-r--r--rsa/pem.py14
-rw-r--r--rsa/pkcs1.py42
-rw-r--r--rsa/prime.py32
-rw-r--r--rsa/randnum.py14
-rw-r--r--rsa/transform.py20
-rw-r--r--rsa/util.py4
-rw-r--r--rsa/varblock.py21
13 files changed, 170 insertions, 167 deletions
diff --git a/rsa/bigfile.py b/rsa/bigfile.py
index ed3fdb9..516cf56 100644
--- a/rsa/bigfile.py
+++ b/rsa/bigfile.py
@@ -13,7 +13,8 @@
# 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 +37,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 +68,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 382a915..f82b245 100644
--- a/rsa/cli.py
+++ b/rsa/cli.py
@@ -14,10 +14,10 @@
# 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
@@ -32,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',
@@ -88,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
@@ -114,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()
@@ -137,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)
@@ -162,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:
@@ -171,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
@@ -182,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
@@ -193,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 '
@@ -205,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 '
@@ -222,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'
@@ -243,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:
@@ -253,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'
@@ -267,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]
@@ -283,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)
@@ -291,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()
@@ -312,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
@@ -325,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
@@ -338,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 '
@@ -349,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 '
@@ -365,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 8667087..39feb8c 100644
--- a/rsa/common.py
+++ b/rsa/common.py
@@ -14,11 +14,11 @@
# 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):
- """
+ '''
Number of bits needed to represent a integer excluding any prefix
0 bits.
@@ -40,7 +40,7 @@ def bit_size(num):
before the number's bit length is determined.
:returns:
Returns the number of bits in the integer.
- """
+ '''
if num == 0:
return 0
if num < 0:
@@ -59,9 +59,9 @@ def bit_size(num):
def _bit_size(number):
- """
+ '''
Returns the number of bits required to hold a specific long number.
- """
+ '''
if number < 0:
raise ValueError('Only nonnegative numbers possible: %s' % number)
@@ -79,7 +79,7 @@ def _bit_size(number):
def byte_size(number):
- """
+ '''
Returns the number of bytes required to hold a specific long number.
The number of bytes is rounded up.
@@ -97,7 +97,7 @@ def byte_size(number):
An unsigned integer
:returns:
The number of bytes required to hold a specific long number.
- """
+ '''
quanta, mod = divmod(bit_size(number), 8)
if mod or number == 0:
quanta += 1
@@ -106,8 +106,8 @@ def byte_size(number):
def extended_gcd(a, b):
- """Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb
- """
+ '''Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb
+ '''
# r = gcd(a,b) i = multiplicitive inverse of a mod b
# or j = multiplicitive inverse of b mod a
# Neg return values for i or j are made positive mod b or a respectively
@@ -129,13 +129,13 @@ def extended_gcd(a, b):
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)
@@ -146,7 +146,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.
@@ -163,7 +163,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 27d829e..90dfee8 100644
--- a/rsa/core.py
+++ b/rsa/core.py
@@ -13,11 +13,12 @@
# 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
@@ -30,7 +31,7 @@ def assert_int(var, name):
raise TypeError('%s should be an integer, not %s' % (name, var.__class__))
def encrypt_int(message, ekey, n):
- """Encrypts a message using encryption key 'ekey', working modulo n"""
+ '''Encrypts a message using encryption key 'ekey', working modulo n'''
assert_int(message, 'message')
assert_int(ekey, 'ekey')
@@ -45,8 +46,8 @@ def encrypt_int(message, ekey, n):
return pow(message, ekey, n)
def decrypt_int(cyphertext, dkey, n):
- """Decrypts a cypher text using the decryption key 'dkey', working
- modulo n"""
+ '''Decrypts a cypher text using the decryption key 'dkey', working
+ modulo n'''
assert_int(cyphertext, 'cyphertext')
assert_int(dkey, 'dkey')
diff --git a/rsa/key.py b/rsa/key.py
index dc4465d..3870541 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
@@ -477,10 +477,10 @@ def find_p_q(nbits, getprime_func=rsa.prime.getprime, accurate=True):
return (max(p, q), min(p, q))
def calculate_keys(p, q, nbits):
- """Calculates an encryption and a decryption key given p and q, and
+ '''Calculates an encryption and a decryption key given p and q, and
returns them as a tuple (e, d)
- """
+ '''
phi_n = (p - 1) * (q - 1)
@@ -500,7 +500,7 @@ def calculate_keys(p, q, nbits):
return (e, d)
def gen_keys(nbits, getprime_func, accurate=True):
- """Generate RSA keys of nbits bits. Returns (p, q, e, d).
+ '''Generate RSA keys of nbits bits. Returns (p, q, e, d).
Note: this can take a long time, depending on the key size.
@@ -508,7 +508,7 @@ def gen_keys(nbits, getprime_func, accurate=True):
``q`` will use ``nbits/2`` bits.
:param getprime_func: either :py:func:`rsa.prime.getprime` or a function
with similar signature.
- """
+ '''
(p, q) = find_p_q(nbits // 2, getprime_func, accurate)
(e, d) = calculate_keys(p, q, nbits // 2)
@@ -516,7 +516,7 @@ def gen_keys(nbits, getprime_func, accurate=True):
return (p, q, e, d)
def newkeys(nbits, accurate=True, poolsize=1):
- """Generates public and private keys, and returns them as (pub, priv).
+ '''Generates public and private keys, and returns them as (pub, priv).
The public key is also known as the 'encryption key', and is a
:py:class:`rsa.PublicKey` object. The private key is also known as the
@@ -535,7 +535,7 @@ def newkeys(nbits, accurate=True, poolsize=1):
The ``poolsize`` parameter was added in *Python-RSA 3.1* and requires
Python 2.6 or newer.
- """
+ '''
if nbits < 16:
raise ValueError('Key too small')
diff --git a/rsa/parallel.py b/rsa/parallel.py
index 8c03f79..d164067 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
@@ -42,7 +42,7 @@ def _find_prime(nbits, pipe):
return
def getprime(nbits, poolsize):
- """Returns a prime number that can be stored in 'nbits' bits.
+ '''Returns a prime number that can be stored in 'nbits' bits.
Works in multiple threads at the same time.
@@ -58,7 +58,7 @@ def getprime(nbits, poolsize):
>>> common.bit_size(p) == 128
True
- """
+ '''
(pipe_recv, pipe_send) = mp.Pipe(duplex=False)
diff --git a/rsa/pem.py b/rsa/pem.py
index 5a37f6d..b1c3a0e 100644
--- a/rsa/pem.py
+++ b/rsa/pem.py
@@ -14,15 +14,15 @@
# 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
- """
+ '''
if is_bytes(pem_marker):
pem_marker = pem_marker.decode('utf-8')
@@ -31,7 +31,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'
@@ -43,7 +43,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)
@@ -93,7 +93,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'
@@ -102,7 +102,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 4c92111..8c6d290 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 141d3df..7422eb1 100644
--- a/rsa/prime.py
+++ b/rsa/prime.py
@@ -14,22 +14,22 @@
# 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']
import rsa.randnum
def gcd(p, q):
- """Returns the greatest common divisor of p and q
+ '''Returns the greatest common divisor of p and q
>>> gcd(48, 180)
12
- """
+ '''
while q != 0:
if p < q: (p,q) = (q,p)
@@ -38,11 +38,11 @@ def gcd(p, q):
def jacobi(a, b):
- """Calculates the value of the Jacobi symbol (a/b) where both a and b are
+ '''Calculates the value of the Jacobi symbol (a/b) where both a and b are
positive integers, and b is odd
:returns: -1, 0 or 1
- """
+ '''
assert a > 0
assert b > 0
@@ -62,9 +62,9 @@ def jacobi(a, b):
return result
def jacobi_witness(x, n):
- """Returns False if n is an Euler pseudo-prime with base x, and
+ '''Returns False if n is an Euler pseudo-prime with base x, and
True otherwise.
- """
+ '''
j = jacobi(x, n) % n
@@ -74,12 +74,12 @@ def jacobi_witness(x, n):
return True
def randomized_primality_testing(n, k):
- """Calculates whether n is composite (which is always correct) or
+ '''Calculates whether n is composite (which is always correct) or
prime (which is incorrect with error probability 2**-k)
Returns False if the number is composite, and True if it's
probably prime.
- """
+ '''
# 50% of Jacobi-witnesses can report compositness of non-prime numbers
@@ -98,18 +98,18 @@ def randomized_primality_testing(n, k):
return True
def is_prime(number):
- """Returns True if the number is prime, and False otherwise.
+ '''Returns True if the number is prime, and False otherwise.
>>> is_prime(42)
False
>>> is_prime(41)
True
- """
+ '''
return randomized_primality_testing(number, 6)
def getprime(nbits):
- """Returns a prime number that can be stored in 'nbits' bits.
+ '''Returns a prime number that can be stored in 'nbits' bits.
>>> p = getprime(128)
>>> is_prime(p-1)
@@ -123,7 +123,7 @@ def getprime(nbits):
>>> common.bit_size(p) == 128
True
- """
+ '''
while True:
integer = rsa.randnum.read_random_int(nbits)
@@ -139,14 +139,14 @@ def getprime(nbits):
def are_relatively_prime(a, b):
- """Returns True if a and b are relatively prime, and False if they
+ '''Returns True if a and b are relatively prime, and False if they
are not.
>>> are_relatively_prime(2, 3)
1
>>> are_relatively_prime(2, 4)
0
- """
+ '''
d = gcd(a, b)
return (d == 1)
diff --git a/rsa/randnum.py b/rsa/randnum.py
index f6494d8..0e78274 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)
@@ -45,8 +45,8 @@ def read_random_bits(nbits):
def read_random_int(nbits):
- """Reads a random integer of approximately nbits bits.
- """
+ '''Reads a random integer of approximately nbits bits.
+ '''
randomdata = read_random_bits(nbits)
value = transform.bytes2int(randomdata)
@@ -58,12 +58,12 @@ def read_random_int(nbits):
return value
def randint(maxvalue):
- """Returns a random integer x with 1 <= x <= maxvalue
+ '''Returns a random integer x with 1 <= x <= maxvalue
May take a very long time in specific situations. If maxvalue needs N bits
to store, the closer maxvalue is to (2 ** N) - 1, the faster this function
is.
- """
+ '''
bit_size = common.bit_size(maxvalue)
diff --git a/rsa/transform.py b/rsa/transform.py
index 7be272c..092b1ca 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
@@ -37,7 +37,7 @@ from rsa._compat import is_integer, b, byte, get_word_alignment, ZERO_BYTE, EMPT
def bytes2int(raw_bytes):
- r"""Converts a list of bytes or an 8-bit string to an integer.
+ r'''Converts a list of bytes or an 8-bit string to an integer.
When using unicode strings, encode it to some encoding like UTF8 first.
@@ -46,13 +46,13 @@ def bytes2int(raw_bytes):
>>> bytes2int('\x80@\x0f')
8405007
- """
+ '''
return int(binascii.hexlify(raw_bytes), 16)
def _int2bytes(number, block_size=None):
- """Converts a number to a string of bytes.
+ '''Converts a number to a string of bytes.
Usage::
@@ -78,7 +78,7 @@ def _int2bytes(number, block_size=None):
@throws OverflowError when block_size is given and the number takes up more
bytes than fit into the block.
- """
+ '''
# Type checking
if not is_integer(number):
raise TypeError("You must pass an integer for 'number', not %s" %
@@ -116,7 +116,7 @@ def _int2bytes(number, block_size=None):
def bytes_leading(raw_bytes, needle=ZERO_BYTE):
- """
+ '''
Finds the number of prefixed byte occurrences in the haystack.
Useful when you want to deal with padding.
@@ -127,7 +127,7 @@ def bytes_leading(raw_bytes, needle=ZERO_BYTE):
The byte to count. Default \000.
:returns:
The number of leading needle bytes.
- """
+ '''
leading = 0
# Indexing keeps compatibility between Python 2.x and Python 3.x
_byte = needle[0]
@@ -140,7 +140,7 @@ def bytes_leading(raw_bytes, needle=ZERO_BYTE):
def int2bytes(number, fill_size=None, chunk_size=None, overflow=False):
- """
+ '''
Convert an unsigned integer to bytes (base-256 representation)::
Does not preserve leading zeros if you don't specify a chunk size or
@@ -172,7 +172,7 @@ def int2bytes(number, fill_size=None, chunk_size=None, overflow=False):
bytes than fit into the block. This requires the ``overflow``
argument to this function to be set to ``False`` otherwise, no
error will be raised.
- """
+ '''
if number < 0:
raise ValueError("Number must be an unsigned integer: %d" % number)
diff --git a/rsa/util.py b/rsa/util.py
index b6df049..307bda5 100644
--- a/rsa/util.py
+++ b/rsa/util.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""Utility functions."""
+'''Utility functions.'''
from __future__ import with_statement
@@ -24,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 d5a342b..34d85a8 100644
--- a/rsa/varblock.py
+++ b/rsa/varblock.py
@@ -13,7 +13,8 @@
# 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 +31,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 +46,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 +68,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 +97,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 +131,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)