diff options
-rw-r--r-- | .gitignore | 1 | ||||
-rw-r--r-- | Doc/epydoc-config | 7 | ||||
-rw-r--r-- | lib/Crypto/Cipher/PKCS1_OAEP.py | 2 | ||||
-rw-r--r-- | lib/Crypto/Cipher/PKCS1_v1_5.py | 2 | ||||
-rw-r--r-- | lib/Crypto/Protocol/KDF.py | 9 | ||||
-rw-r--r-- | lib/Crypto/PublicKey/DSA.py | 199 | ||||
-rw-r--r-- | lib/Crypto/PublicKey/ElGamal.py | 300 | ||||
-rw-r--r-- | lib/Crypto/PublicKey/RSA.py | 181 | ||||
-rw-r--r-- | lib/Crypto/PublicKey/__init__.py | 7 | ||||
-rw-r--r-- | lib/Crypto/PublicKey/pubkey.py | 122 | ||||
-rw-r--r-- | lib/Crypto/PublicKey/qNEW.py | 2 | ||||
-rw-r--r-- | lib/Crypto/Signature/PKCS1_PSS.py | 2 | ||||
-rw-r--r-- | lib/Crypto/Signature/PKCS1_v1_5.py | 2 |
13 files changed, 733 insertions, 103 deletions
@@ -14,6 +14,7 @@ MANIFEST /config.h /config.log /config.status +src/config.h # Backup files *~ diff --git a/Doc/epydoc-config b/Doc/epydoc-config index 018e461..c71d200 100644 --- a/Doc/epydoc-config +++ b/Doc/epydoc-config @@ -8,6 +8,13 @@ output: html target: Doc/apidoc/ sourcecode: no +# Do not include private variables +private: no + +# Include the complete set of inherited methods, but grouped in a special +# section +inheritance: grouped + name: PyCrypto API Documentation url: http://www.pycrypto.org/ diff --git a/lib/Crypto/Cipher/PKCS1_OAEP.py b/lib/Crypto/Cipher/PKCS1_OAEP.py index f02609d..9afe176 100644 --- a/lib/Crypto/Cipher/PKCS1_OAEP.py +++ b/lib/Crypto/Cipher/PKCS1_OAEP.py @@ -52,7 +52,7 @@ the RSA key: from __future__ import nested_scopes __revision__ = "$Id$" -__all__ = [ 'new' ] +__all__ = [ 'new', 'PKCS1OAEP_Cipher' ] import Crypto.Signature.PKCS1_PSS import Crypto.Hash.SHA diff --git a/lib/Crypto/Cipher/PKCS1_v1_5.py b/lib/Crypto/Cipher/PKCS1_v1_5.py index 3f860ee..c89035d 100644 --- a/lib/Crypto/Cipher/PKCS1_v1_5.py +++ b/lib/Crypto/Cipher/PKCS1_v1_5.py @@ -68,7 +68,7 @@ the RSA key: """ __revision__ = "$Id$" -__all__ = [ 'new' ] +__all__ = [ 'new', 'PKCS115_Cipher' ] from Crypto.Util.number import ceil_div from Crypto.Util.py3compat import * diff --git a/lib/Crypto/Protocol/KDF.py b/lib/Crypto/Protocol/KDF.py index c6979c8..973b7af 100644 --- a/lib/Crypto/Protocol/KDF.py +++ b/lib/Crypto/Protocol/KDF.py @@ -42,7 +42,7 @@ from Crypto.Util.py3compat import * from Crypto.Hash import SHA as SHA1, HMAC from Crypto.Util.strxor import strxor -def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=SHA1): +def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=None): """Derive one key from a password (or passphrase). This function performs key derivation according an old version of @@ -66,14 +66,17 @@ def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=SHA1): hashAlgo : module The hash algorithm to use, as a module or an object from the `Crypto.Hash` package. The digest length must be no shorter than ``dkLen``. + The default algorithm is `SHA1`. :Return: A byte string of length `dkLen` that can be used as key. -""" + """ + if not hashAlgo: + hashAlgo = SHA1 password = tobytes(password) pHash = hashAlgo.new(password+salt) digest = pHash.digest_size if dkLen>digest: - raise ValueError("Selected hash algorithm has a too short digest (%d bytes)." % len(digest)) + raise ValueError("Selected hash algorithm has a too short digest (%d bytes)." % digest) if len(salt)!=8: raise ValueError("Salt is not 8 bytes long.") for i in xrange(count-1): diff --git a/lib/Crypto/PublicKey/DSA.py b/lib/Crypto/PublicKey/DSA.py index 5c349a9..d6bffd6 100644 --- a/lib/Crypto/PublicKey/DSA.py +++ b/lib/Crypto/PublicKey/DSA.py @@ -22,11 +22,64 @@ # SOFTWARE. # =================================================================== -"""DSA public-key signature algorithm.""" +"""DSA public-key signature algorithm. + +DSA_ is a widespread public-key signature algorithm. Its security is +based on the discrete logarithm problem (DLP_). Given a cyclic +group, a generator *g*, and an element *h*, it is hard +to find an integer *x* such that *g^x = h*. The problem is believed +to be difficult, and it has been proved such (and therefore secure) for +more than 30 years. + +The group is actually a sub-group over the integers modulo *p*, with *p* prime. +The sub-group order is *q*, which is prime too; it always holds that *(p-1)* is a multiple of *q*. +The cryptographic strength is linked to the magnitude of *p* and *q*. +The signer holds a value *x* (*0<x<q-1*) as private key, and its public +key (*y* where *y=g^x mod p*) is distributed. + +In 2012, a sufficient size is deemed to be 2048 bits for *p* and 256 bits for *q*. +For more information, see the most recent ECRYPT_ report. + +DSA is reasonably secure for new designs. + +The algorithm can only be used for authentication (digital signature). +DSA cannot be used for confidentiality (encryption). + +The values *(p,q,g)* are called *domain parameters*; +they are not sensitive but must be shared by both parties (the signer and the verifier). +Different signers can share the same domain parameters with no security +concerns. + +The DSA signature is twice as big as the size of *q* (64 bytes if *q* is 256 bit +long). + +This module provides facilities for generating new DSA keys and for constructing +them from known components. DSA keys allows you to perform basic signing and +verification. + + >>> from Crypto.Random import random + >>> from Crypto.PublicKey import DSA + >>> from Crypto.Hash import SHA + >>> + >>> message = "Hello" + >>> key = DSA.generate(1024) + >>> h = SHA.new(message).digest() + >>> k = random.StrongRandom().randint(1,key.q-1) + >>> sig = key.sign(h,k) + >>> ... + >>> if key.verify(h,sig): + >>> print "OK" + >>> else: + >>> print "Incorrect signature" + +.. _DSA: http://en.wikipedia.org/wiki/Digital_Signature_Algorithm +.. _DLP: http://www.cosic.esat.kuleuven.be/publications/talk-78.pdf +.. _ECRYPT: http://www.ecrypt.eu.org/documents/D.SPA.17.pdf +""" __revision__ = "$Id$" -__all__ = ['generate', 'construct', 'error'] +__all__ = ['generate', 'construct', 'error', 'DSAImplementation', '_DSAobj'] import sys if sys.version_info[0] == 2 and sys.version_info[1] == 1: @@ -41,6 +94,22 @@ except ImportError: _fastmath = None class _DSAobj(pubkey.pubkey): + """Class defining an actual DSA key. + + :undocumented: __getstate__, __setstate__, __repr__, __getattr__ + """ + #: Dictionary of DSA parameters. + #: + #: A public key will only have the following entries: + #: + #: - **y**, the public key. + #: - **g**, the generator. + #: - **p**, the modulus. + #: - **q**, the order of the sub-group. + #: + #: A private key will also have: + #: + #: - **x**, the private key. keydata = ['y', 'g', 'p', 'q', 'x'] def __init__(self, implementation, key): @@ -55,6 +124,50 @@ class _DSAobj(pubkey.pubkey): else: raise AttributeError("%s object has no %r attribute" % (self.__class__.__name__, attrname,)) + def sign(self, M, K): + """Sign a piece of data with DSA. + + :Parameter M: The piece of data to sign with DSA. It may + not be longer in bit size than the sub-group order (*q*). + :Type M: byte string or long + + :Parameter K: A secret number, chosen randomly in the closed + range *[1,q-1]*. + :Type K: long (recommended) or byte string (not recommended) + + :attention: selection of *K* is crucial for security. Generating a + random number larger than *q* and taking the modulus by *q* is + **not** secure, since smaller values will occur more frequently. + Generating a random number systematically smaller than *q-1* + (e.g. *floor((q-1)/8)* random bytes) is also **not** secure. In general, + it shall not be possible for an attacker to know the value of `any + bit of K`__. + + :attention: The number *K* shall not be reused for any other + operation and shall be discarded immediately. + + :attention: M must be a digest cryptographic hash, otherwise + an attacker may mount an existential forgery attack. + + :Return: A tuple with 2 longs. + + .. __: http://www.di.ens.fr/~pnguyen/pub_NgSh00.htm + """ + return pubkey.pubkey.sign(self, M, K) + + def verify(self, M, signature): + """Verify the validity of a DSA signature. + + :Parameter M: The expected message. + :Type M: byte string or long + + :Parameter signature: The DSA signature to verify. + :Type signature: A tuple with 2 longs as return by `sign` + + :Return: True if the signature is correct, False otherwise. + """ + return pubkey.pubkey.verify(self, M, signature) + def _encrypt(self, c, K): raise TypeError("DSA cannot encrypt") @@ -124,11 +237,31 @@ class _DSAobj(pubkey.pubkey): return "<%s @0x%x %s>" % (self.__class__.__name__, id(self), ",".join(attrs)) class DSAImplementation(object): + """ + A DSA key factory. + + This class is only internally used to implement the methods of the + `Crypto.PublicKey.DSA` module. + """ + def __init__(self, **kwargs): - # 'use_fast_math' parameter: - # None (default) - Use fast math if available; Use slow math if not. - # True - Use fast math, and raise RuntimeError if it's not available. - # False - Use slow math. + """Create a new DSA key factory. + + :Keywords: + use_fast_math : bool + Specify which mathematic library to use: + + - *None* (default). Use fastest math available. + - *True* . Use fast math. + - *False* . Use slow math. + default_randfunc : callable + Specify how to collect random data: + + - *None* (default). Use Random.new().read(). + - not *None* . Use the specified function directly. + :Raise RuntimeError: + When **use_fast_math** =True but fast math is not available. + """ use_fast_math = kwargs.get('use_fast_math', None) if use_fast_math is None: # Automatic if _fastmath is not None: @@ -161,6 +294,36 @@ class DSAImplementation(object): return self._current_randfunc def generate(self, bits, randfunc=None, progress_func=None): + """Randomly generate a fresh, new DSA key. + + :Parameters: + bits : int + Key length, or size (in bits) of the DSA modulus + *p*. + It must be a multiple of 64, in the closed + interval [512,1024]. + randfunc : callable + Random number generation function; it should accept + a single integer N and return a string of random data + N bytes long. + If not specified, a new one will be instantiated + from ``Crypto.Random``. + progress_func : callable + Optional function that will be called with a short string + containing the key parameter currently being generated; + it's useful for interactive applications where a user is + waiting for a key to be generated. + + :attention: You should always use a cryptographically secure random number generator, + such as the one defined in the ``Crypto.Random`` module; **don't** just use the + current time and the ``random`` module. + + :Return: A DSA key object (`_DSAobj`). + + :Raise ValueError: + When **bits** is too little, too big, or not a multiple of 64. + """ + # Check against FIPS 186-2, which says that the size of the prime p # must be a multiple of 64 bits between 512 and 1024 for i in (0, 1, 2, 3, 4, 5, 6, 7, 8): @@ -180,6 +343,30 @@ class DSAImplementation(object): return _DSAobj(self, key) def construct(self, tup): + """Construct a DSA key from a tuple of valid DSA components. + + The modulus *p* must be a prime. + + The following equations must apply: + + - p-1 = 0 mod q + - g^x = y mod p + - 0 < x < q + - 1 < g < p + + :Parameters: + tup : tuple + A tuple of long integers, with 4 or 5 items + in the following order: + + 1. Public key (*y*). + 2. Sub-group generator (*g*). + 3. Modulus, finite field order (*p*). + 4. Sub-group order (*q*). + 5. Private key (*x*). Optional. + + :Return: A DSA key object (`_DSAobj`). + """ key = self._math.dsa_construct(*tup) return _DSAobj(self, key) diff --git a/lib/Crypto/PublicKey/ElGamal.py b/lib/Crypto/PublicKey/ElGamal.py index 793d970..1a157ce 100644 --- a/lib/Crypto/PublicKey/ElGamal.py +++ b/lib/Crypto/PublicKey/ElGamal.py @@ -23,8 +23,92 @@ # SOFTWARE. # =================================================================== +"""ElGamal public-key algorithm (randomized encryption and signature). + +Signature algorithm +------------------- +The security of the ElGamal signature scheme is based (like DSA) on the discrete +logarithm problem (DLP_). Given a cyclic group, a generator *g*, +and an element *h*, it is hard to find an integer *x* such that *g^x = h*. + +The group is the largest multiplicative sub-group of the integers modulo *p*, +with *p* prime. +The signer holds a value *x* (*0<x<p-1*) as private key, and its public +key (*y* where *y=g^x mod p*) is distributed. + +The ElGamal signature is twice as big as *p*. + +Encryption algorithm +-------------------- +The security of the ElGamal encryption scheme is based on the computational +Diffie-Hellman problem (CDH_). Given a cyclic group, a generator *g*, +and two integers *a* and *b*, it is difficult to find +the element *g^{ab}* when only *g^a* and *g^b* are known, and not *a* and *b*. + +As before, the group is the largest multiplicative sub-group of the integers +modulo *p*, with *p* prime. +The receiver holds a value *a* (*0<a<p-1*) as private key, and its public key +(*b* where *b*=g^a*) is given to the sender. + +The ElGamal ciphertext is twice as big as *p*. + +Domain parameters +----------------- +For both signature and encryption schemes, the values *(p,g)* are called +*domain parameters*. +They are not sensitive but must be distributed to all parties (senders and +receivers). +Different signers can share the same domain parameters, as can +different recipients of encrypted messages. + +Security +-------- +Both DLP and CDH problem are believed to be difficult, and they have been proved +such (and therefore secure) for more than 30 years. + +The cryptographic strength is linked to the magnitude of *p*. +In 2012, a sufficient size for *p* is deemed to be 2048 bits. +For more information, see the most recent ECRYPT_ report. + +Even though ElGamal algorithms are in theory reasonably secure for new designs, +in practice there are no real good reasons for using them. +The signature is four times larger than the equivalent DSA, and the ciphertext +is two times larger than the equivalent RSA. + +Functionality +------------- +This module provides facilities for generating new ElGamal keys and for constructing +them from known components. ElGamal keys allows you to perform basic signing, +verification, encryption, and decryption. + + >>> from Crypto import Random + >>> from Crypto.Random import random + >>> from Crypto.PublicKey import ElGamal + >>> from Crypto.Util.number import GCD + >>> from Crypto.Hash import SHA + >>> + >>> message = "Hello" + >>> key = ElGamal.generate(1024, Random.new().read) + >>> h = SHA.new(message).digest() + >>> while 1: + >>> k = random.StrongRandom().randint(1,key.p-1) + >>> if GCD(k,key.p-1)==1: break + >>> sig = key.sign(h,k) + >>> ... + >>> if key.verify(h,sig): + >>> print "OK" + >>> else: + >>> print "Incorrect signature" + +.. _DLP: http://www.cosic.esat.kuleuven.be/publications/talk-78.pdf +.. _CDH: http://en.wikipedia.org/wiki/Computational_Diffie%E2%80%93Hellman_assumption +.. _ECRYPT: http://www.ecrypt.eu.org/documents/D.SPA.17.pdf +""" + __revision__ = "$Id$" +__all__ = ['generate', 'construct', 'error', 'ElGamalobj'] + from Crypto.PublicKey.pubkey import * from Crypto.Util import number @@ -33,53 +117,102 @@ class error (Exception): # Generate an ElGamal key with N bits def generate(bits, randfunc, progress_func=None): - """generate(bits:int, randfunc:callable, progress_func:callable) + """Randomly generate a fresh, new ElGamal key. + + The key will be safe for use for both encryption and signature + (although it should be used for **only one** purpose). - Generate an ElGamal key of length 'bits', using 'randfunc' to get - random data and 'progress_func', if present, to display - the progress of the key generation. + :Parameters: + bits : int + Key length, or size (in bits) of the modulus *p*. + Recommended value is 2048. + randfunc : callable + Random number generation function; it should accept + a single integer N and return a string of random data + N bytes long. + progress_func : callable + Optional function that will be called with a short string + containing the key parameter currently being generated; + it's useful for interactive applications where a user is + waiting for a key to be generated. + + :attention: You should always use a cryptographically secure random number generator, + such as the one defined in the ``Crypto.Random`` module; **don't** just use the + current time and the ``random`` module. + + :Return: An ElGamal key object (`ElGamalobj`). """ obj=ElGamalobj() - # Generate prime p + # Generate a safe prime p + # See Algorithm 4.86 in Handbook of Applied Cryptography if progress_func: progress_func('p\n') - obj.p=bignum(getPrime(bits, randfunc)) - # Generate random number g + while 1: + q = bignum(getPrime(bits-1, randfunc)) + obj.p = 2*q+1 + if number.isPrime(obj.p, randfunc=randfunc): + break + # Generate generator g + # See Algorithm 4.80 in Handbook of Applied Cryptography + # Note that the order of the group is n=p-1=2q, where q is prime if progress_func: progress_func('g\n') - size=bits-1-(ord(randfunc(1)) & 63) # g will be from 1--64 bits smaller than p - if size<1: - size=bits-1 - while (1): - obj.g=bignum(getPrime(size, randfunc)) - if obj.g < obj.p: + while 1: + # We must avoid g=2 because of Bleichenbacher's attack described + # in "Generating ElGamal signatures without knowning the secret key", + # 1996 + # + obj.g = number.getRandomRange(3, obj.p, randfunc) + safe = 1 + if pow(obj.g, 2, obj.p)==1: + safe=0 + if safe and pow(obj.g, q, obj.p)==1: + safe=0 + # Discard g if it divides p-1 because of the attack described + # in Note 11.67 (iii) in HAC + if safe and divmod(obj.p-1, obj.g)[1]==0: + safe=0 + # g^{-1} must not divide p-1 because of Khadir's attack + # described in "Conditions of the generator for forging ElGamal + # signature", 2011 + ginv = number.inverse(obj.g, obj.p) + if safe and divmod(obj.p-1, ginv)[1]==0: + safe=0 + if safe: break - size=(size+1) % bits - if size==0: - size=4 - # Generate random number x + # Generate private key x if progress_func: progress_func('x\n') - while (1): - size=bits-1-ord(randfunc(1)) # x will be from 1 to 256 bits smaller than p - if size>2: - break - while (1): - obj.x=bignum(getPrime(size, randfunc)) - if obj.x < obj.p: - break - size = (size+1) % bits - if size==0: - size=4 + obj.x=number.getRandomRange(2, obj.p-1, randfunc) + # Generate public key y if progress_func: progress_func('y\n') obj.y = pow(obj.g, obj.x, obj.p) return obj -def construct(tuple): - """construct(tuple:(long,long,long,long)|(long,long,long,long,long))) - : ElGamalobj - Construct an ElGamal key from a 3- or 4-tuple of numbers. +def construct(tup): + """Construct an ElGamal key from a tuple of valid ElGamal components. + + The modulus *p* must be a prime. + + The following conditions must apply: + + - 1 < g < p-1 + - g^{p-1} = 1 mod p + - 1 < x < p-1 + - g^x = y mod p + + :Parameters: + tup : tuple + A tuple of long integers, with 3 or 4 items + in the following order: + + 1. Modulus (*p*). + 2. Generator (*g*). + 3. Public key (*y*). + 4. Private key (*x*). Optional. + + :Return: An ElGamal key object (`ElGamalobj`). """ obj=ElGamalobj() @@ -91,8 +224,105 @@ def construct(tuple): return obj class ElGamalobj(pubkey): + """Class defining an ElGamal key. + + :undocumented: __getstate__, __setstate__, __repr__, __getattr__ + """ + + #: Dictionary of ElGamal parameters. + #: + #: A public key will only have the following entries: + #: + #: - **y**, the public key. + #: - **g**, the generator. + #: - **p**, the modulus. + #: + #: A private key will also have: + #: + #: - **x**, the private key. keydata=['p', 'g', 'y', 'x'] + def encrypt(self, plaintext, K): + """Encrypt a piece of data with ElGamal. + + :Parameter plaintext: The piece of data to encrypt with ElGamal. + It must be numerically smaller than the module (*p*). + :Type plaintext: byte string or long + + :Parameter K: A secret number, chosen randomly in the closed + range *[1,p-2]*. + :Type K: long (recommended) or byte string (not recommended) + + :Return: A tuple with two items. Each item is of the same type as the + plaintext (string or long). + + :attention: selection of *K* is crucial for security. Generating a + random number larger than *p-1* and taking the modulus by *p-1* is + **not** secure, since smaller values will occur more frequently. + Generating a random number systematically smaller than *p-1* + (e.g. *floor((p-1)/8)* random bytes) is also **not** secure. + In general, it shall not be possible for an attacker to know + the value of any bit of K. + + :attention: The number *K* shall not be reused for any other + operation and shall be discarded immediately. + """ + return pubkey.encrypt(self, plaintext, K) + + def decrypt(self, ciphertext): + """Decrypt a piece of data with ElGamal. + + :Parameter ciphertext: The piece of data to decrypt with ElGamal. + :Type ciphertext: byte string, long or a 2-item tuple as returned + by `encrypt` + + :Return: A byte string if ciphertext was a byte string or a tuple + of byte strings. A long otherwise. + """ + return pubkey.decrypt(self, ciphertext) + + def sign(self, M, K): + """Sign a piece of data with ElGamal. + + :Parameter M: The piece of data to sign with ElGamal. It may + not be longer in bit size than *p-1*. + :Type M: byte string or long + + :Parameter K: A secret number, chosen randomly in the closed + range *[1,p-2]* and such that *gcd(k,p-1)=1*. + :Type K: long (recommended) or byte string (not recommended) + + :attention: selection of *K* is crucial for security. Generating a + random number larger than *p-1* and taking the modulus by *p-1* is + **not** secure, since smaller values will occur more frequently. + Generating a random number systematically smaller than *p-1* + (e.g. *floor((p-1)/8)* random bytes) is also **not** secure. + In general, it shall not be possible for an attacker to know + the value of any bit of K. + + :attention: The number *K* shall not be reused for any other + operation and shall be discarded immediately. + + :attention: M must be be a cryptographic hash, otherwise an + attacker may mount an existential forgery attack. + + :Return: A tuple with 2 longs. + """ + return pubkey.sign(self, M, K) + + def verify(self, M, signature): + """Verify the validity of an ElGamal signature. + + :Parameter M: The expected message. + :Type M: byte string or long + + :Parameter signature: The ElGamal signature to verify. + :Type signature: A tuple with 2 longs as return by `sign` + + :Return: True if the signature is correct, False otherwise. + """ + return pubkey.verify(self, M, signature) + def _encrypt(self, M, K): a=pow(self.g, K, self.p) b=( M*pow(self.y, K, self.p) ) % self.p @@ -118,6 +348,8 @@ class ElGamalobj(pubkey): return (a, b) def _verify(self, M, sig): + if sig[0]<1 or sig[0]>p-1: + return 0 v1=pow(self.y, sig[0], self.p) v1=(v1*pow(sig[0], sig[1], self.p)) % self.p v2=pow(self.g, M, self.p) @@ -126,19 +358,15 @@ class ElGamalobj(pubkey): return 0 def size(self): - "Return the maximum number of bits that can be handled by this key." return number.size(self.p) - 1 def has_private(self): - """Return a Boolean denoting whether the object contains - private components.""" if hasattr(self, 'x'): return 1 else: return 0 def publickey(self): - """Return a new key object containing only the public information.""" return construct((self.p, self.g, self.y)) diff --git a/lib/Crypto/PublicKey/RSA.py b/lib/Crypto/PublicKey/RSA.py index 1e3a433..4f40ec0 100644 --- a/lib/Crypto/PublicKey/RSA.py +++ b/lib/Crypto/PublicKey/RSA.py @@ -22,15 +22,50 @@ # SOFTWARE. # =================================================================== -"""RSA public-key cryptography algorithm. +"""RSA public-key cryptography algorithm (signature and encryption). + +RSA_ is the most widespread and used public key algorithm. Its security is +based on the difficulty of factoring large integers. The algorithm has +withstood attacks for 30 years, and it is therefore considered reasonably +secure for new designs. + +The algorithm can be used for both confidentiality (encryption) and +authentication (digital signature). It is worth noting that signing and +decryption are significantly slower than verification and encryption. +The cryptograhic strength is primarily linked to the length of the modulus *n*. +In 2012, a sufficient length is deemed to be 2048 bits. For more information, +see the most recent ECRYPT_ report. + +Both RSA ciphertext and RSA signature are as big as the modulus *n* (256 +bytes if *n* is 2048 bit long). + +This module provides facilities for generating fresh, new RSA keys, constructing +them from known components, exporting them, and importing them. + + >>> from Crypto.PublicKey import RSA + >>> + >>> key = RSA.generate(2048) + >>> f = open('mykey.pem','w') + >>> f.write(RSA.exportKey('PEM')) + >>> f.close() + ... + >>> f = open('mykey.pem','r') + >>> key = RSA.importKey(f.read()) + +Even though you may choose to directly use the methods of an RSA key object +to perform the primitive cryptographic operations (e.g. `_RSAobj.encrypt`), +it is recommended to use one of the standardized schemes instead (like +`Crypto.Cipher.PKCS1_v1_5` or `Crypto.Signature.PKCS1_v1_5`). + +.. _RSA: http://en.wikipedia.org/wiki/RSA_%28algorithm%29 +.. _ECRYPT: http://www.ecrypt.eu.org/documents/D.SPA.17.pdf :sort: generate,construct,importKey,error -:undocumented: _fastmath, __revision__, _impl """ __revision__ = "$Id$" -__all__ = ['generate', 'construct', 'error', 'importKey' ] +__all__ = ['generate', 'construct', 'error', 'importKey', 'RSAImplementation', '_RSAobj'] import sys if sys.version_info[0] == 2 and sys.version_info[1] == 1: @@ -56,8 +91,10 @@ except ImportError: _fastmath = None class _RSAobj(pubkey.pubkey): - """Class defining an actual RSA key.""" + """Class defining an actual RSA key. + :undocumented: __getstate__, __setstate__, __repr__, __getattr__ + """ #: Dictionary of RSA parameters. #: #: A public key will only have the following entries: @@ -88,6 +125,101 @@ class _RSAobj(pubkey.pubkey): else: raise AttributeError("%s object has no %r attribute" % (self.__class__.__name__, attrname,)) + def encrypt(self, plaintext, K): + """Encrypt a piece of data with RSA. + + :Parameter plaintext: The piece of data to encrypt with RSA. It may not + be numerically larger than the RSA module (**n**). + :Type plaintext: byte string or long + + :Parameter K: A random parameter (*for compatibility only. This + value will be ignored*) + :Type K: byte string or long + + :attention: this function performs the plain, primitive RSA encryption + (*textbook*). In real applications, you always need to use proper + cryptographic padding, and you should not directly encrypt data with + this method. Failure to do so may lead to security vulnerabilities. + It is recommended to use modules + `Crypto.Cipher.PKCS1_OAEP` or `Crypto.Cipher.PKCS1_v1_5` instead. + + :Return: A tuple with two items. The first item is the ciphertext + of the same type as the plaintext (string or long). The second item + is always None. + """ + return pubkey.pubkey.encrypt(self, plaintext, K) + + def decrypt(self, ciphertext): + """Decrypt a piece of data with RSA. + + Decryption always takes place with blinding. + + :attention: this function performs the plain, primitive RSA decryption + (*textbook*). In real applications, you always need to use proper + cryptographic padding, and you should not directly decrypt data with + this method. Failure to do so may lead to security vulnerabilities. + It is recommended to use modules + `Crypto.Cipher.PKCS1_OAEP` or `Crypto.Cipher.PKCS1_v1_5` instead. + + :Parameter ciphertext: The piece of data to decrypt with RSA. It may + not be numerically larger than the RSA module (**n**). If a tuple, + the first item is the actual ciphertext; the second item is ignored. + + :Type ciphertext: byte string, long or a 2-item tuple as returned by + `encrypt` + + :Return: A byte string if ciphertext was a byte string or a tuple + of byte strings. A long otherwise. + """ + return pubkey.pubkey.decrypt(self, ciphertext) + + def sign(self, M, K): + """Sign a piece of data with RSA. + + Signing always takes place with blinding. + + :attention: this function performs the plain, primitive RSA decryption + (*textbook*). In real applications, you always need to use proper + cryptographic padding, and you should not directly sign data with + this method. Failure to do so may lead to security vulnerabilities. + It is recommended to use modules + `Crypto.Signature.PKCS1_PSS` or `Crypto.Signature.PKCS1_v1_5` instead. + + :Parameter M: The piece of data to sign with RSA. It may + not be numerically larger than the RSA module (**n**). + :Type M: byte string or long + + :Parameter K: A random parameter (*for compatibility only. This + value will be ignored*) + :Type K: byte string or long + + :Return: A 2-item tuple. The first item is the actual signature (a + long). The second item is always None. + """ + return pubkey.pubkey.sign(self, M, K) + + def verify(self, M, signature): + """Verify the validity of an RSA signature. + + :attention: this function performs the plain, primitive RSA encryption + (*textbook*). In real applications, you always need to use proper + cryptographic padding, and you should not directly verify data with + this method. Failure to do so may lead to security vulnerabilities. + It is recommended to use modules + `Crypto.Signature.PKCS1_PSS` or `Crypto.Signature.PKCS1_v1_5` instead. + + :Parameter M: The expected message. + :Type M: byte string or long + + :Parameter signature: The RSA signature to verify. The first item of + the tuple is the actual signature (a long not larger than the modulus + **n**), whereas the second item is always ignored. + :Type signature: A 2-item tuple as return by `sign` + + :Return: True if the signature is correct, False otherwise. + """ + return pubkey.pubkey.verify(self, M, signature) + def _encrypt(self, c, K): return (self.key._encrypt(c),) @@ -179,7 +311,7 @@ class _RSAobj(pubkey.pubkey): :Parameter format: The format to use for wrapping the key. - *'DER'*. Binary encoding, always unencrypted. - - *'PEM'*. Textual encoding, done according to RFC1421/3. + - *'PEM'*. Textual encoding, done according to `RFC1421`_/`RFC1423`_. Unencrypted (default) or encrypted. - *'OpenSSH'*. Textual encoding, done according to OpenSSH specification. Only suitable for public keys (not private keys). @@ -189,15 +321,20 @@ class _RSAobj(pubkey.pubkey): :Type passphrase: string :Parameter pkcs: The PKCS standard to follow for encoding the key. - You have two choices: **1** (PKCS#1, RFC3447) or **8** (PKCS#8, RFC5208). + You have two choices: **1** (PKCS#1, `RFC3447`_) or **8** (PKCS#8, `RFC5208`_). PKCS#8 is only available for private keys. PKCS#1 is the default. PKCS standards are not relevant for the *OpenSSH* format. :Type pkcs: integer - :Return: A string with the encoded public or private half. + :Return: A byte string with the encoded public or private half. :Raise ValueError: When the format is unknown. + + .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt + .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt + .. _RFC3447: http://www.ietf.org/rfc/rfc3447.txt + .. _RFC5208: http://www.ietf.org/rfc/rfc5208.txt """ if passphrase is not None: passphrase = tobytes(passphrase) @@ -264,7 +401,7 @@ class RSAImplementation(object): """ An RSA key factory. - This class is only internally used to implement the methods of the `Crypto.PublicKey.RSA` modulule. + This class is only internally used to implement the methods of the `Crypto.PublicKey.RSA` module. :sort: __init__,generate,construct,importKey :undocumented: _g*, _i* @@ -284,7 +421,7 @@ class RSAImplementation(object): Specify how to collect random data: - *None* (default). Use Random.new().read(). - - not *Note* . Use the specified function directly. + - not *None* . Use the specified function directly. :Raise RuntimeError: When **use_fast_math** =True but fast math is not available. """ @@ -317,28 +454,30 @@ class RSAImplementation(object): return self._current_randfunc def generate(self, bits, randfunc=None, progress_func=None, e=65537): - """Randomly generate a fresh, new RSA key object. + """Randomly generate a fresh, new RSA key. :Parameters: bits : int Key length, or size (in bits) of the RSA modulus. - It must be a multiple of 256, and no smaller than 1024. + randfunc : callable Random number generation function; it should accept a single integer N and return a string of random data N bytes long. + If not specified, a new one will be instantiated + from ``Crypto.Random``. + progress_func : callable Optional function that will be called with a short string containing the key parameter currently being generated; it's useful for interactive applications where a user is waiting for a key to be generated. + e : int Public RSA exponent. It must be an odd positive integer. - It is typically a small number with very few ones in its binary representation. - The default value 65537 (= ``0b10000000000000001`` ) is a safe choice: other common values are 5, 7, 17, and 257. @@ -349,6 +488,8 @@ class RSAImplementation(object): :attention: Exponent 3 is also widely used, but it requires very special care when padding the message. + :Return: An RSA key object (`_RSAobj`). + :Raise ValueError: When **bits** is too little or not a multiple of 256, or when **e** is not odd or smaller than 2. @@ -364,7 +505,7 @@ class RSAImplementation(object): return _RSAobj(self, key) def construct(self, tup): - """Construct an RSA key object from a tuple of valid RSA components. + """Construct an RSA key from a tuple of valid RSA components. The modulus **n** must be the product of two primes. The public exponent **e** must be odd and larger than 1. @@ -387,6 +528,8 @@ class RSAImplementation(object): 4. First factor of n (p). Optional. 5. Second factor of n (q). Optional. 6. CRT coefficient, (1/p) mod q (u). Optional. + + :Return: An RSA key object (`_RSAobj`). """ key = self._math.rsa_construct(*tup) return _RSAobj(self, key) @@ -445,9 +588,9 @@ class RSAImplementation(object): The key can be in any of the following formats: - DER + PKCS#1 (binary) - - PEM + PKCS#1 (textual, according to RFC1421/3) + - PEM + PKCS#1 (textual, according to `RFC1421`_/`RFC1423`_) - DER + PKCS#8 (binary, private key only) - - PEM + PKCS#8 (textual, according to RFC5208, private key only) + - PEM + PKCS#8 (textual, according to `RFC5208`_, private key only) - OpenSSH (textual public key only) In case of PEM + PKCS#1, the key can be encrypted with DES or 3TDES according to a certain ``pass phrase``. @@ -458,8 +601,14 @@ class RSAImplementation(object): In case of an encrypted PEM key, this is the pass phrase from which the encryption key is derived. :Type passphrase: string + :Return: An RSA key object (`_RSAobj`). + :Raise ValueError/IndexError/TypeError: When the given key cannot be parsed (possibly because the pass phrase is wrong). + + .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt + .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt + .. _RFC5208: http://www.ietf.org/rfc/rfc5208.txt """ externKey = tobytes(externKey) if passphrase is not None: diff --git a/lib/Crypto/PublicKey/__init__.py b/lib/Crypto/PublicKey/__init__.py index 68e1d88..f966270 100644 --- a/lib/Crypto/PublicKey/__init__.py +++ b/lib/Crypto/PublicKey/__init__.py @@ -25,11 +25,16 @@ one for decryption. The encryption key can be made public, and the decryption key is kept private. Many public-key algorithms can also be used to sign messages, and some can *only* be used for signatures. -Crypto.PublicKey.DSA Digital Signature Algorithm. (Signature only) +======================== ============================================= +Module Description +======================== ============================================= +Crypto.PublicKey.DSA Digital Signature Algorithm (Signature only) Crypto.PublicKey.ElGamal (Signing and encryption) Crypto.PublicKey.RSA (Signing, encryption, and blinding) Crypto.PublicKey.qNEW (Signature only) +======================== ============================================= +:undocumented: _DSA, _RSA, _fastmath, _slowmath, pubkey """ __all__ = ['RSA', 'DSA', 'ElGamal', 'qNEW'] diff --git a/lib/Crypto/PublicKey/pubkey.py b/lib/Crypto/PublicKey/pubkey.py index 90f4603..e44de8f 100644 --- a/lib/Crypto/PublicKey/pubkey.py +++ b/lib/Crypto/PublicKey/pubkey.py @@ -31,6 +31,10 @@ from Crypto.Util.number import * # Basic public key class class pubkey: + """An abstract class for a public key object. + + :undocumented: __getstate__, __setstate__, __eq__, __ne__, validate + """ def __init__(self): pass @@ -52,9 +56,16 @@ integers, MPZ objects, or whatever.""" if d.has_key(key): self.__dict__[key]=bignum(d[key]) def encrypt(self, plaintext, K): - """encrypt(plaintext:string|long, K:string|long) : tuple - Encrypt the string or integer plaintext. K is a random - parameter required by some algorithms. + """Encrypt a piece of data. + + :Parameter plaintext: The piece of data to encrypt. + :Type plaintext: byte string or long + + :Parameter K: A random parameter required by some algorithms + :Type K: byte string or long + + :Return: A tuple with two items. Each item is of the same type as the + plaintext (string or long). """ wasString=0 if isinstance(plaintext, types.StringType): @@ -66,8 +77,13 @@ integers, MPZ objects, or whatever.""" else: return ciphertext def decrypt(self, ciphertext): - """decrypt(ciphertext:tuple|string|long): string - Decrypt 'ciphertext' using this key. + """Decrypt a piece of data. + + :Parameter ciphertext: The piece of data to decrypt. + :Type ciphertext: byte string, long or a 2-item tuple as returned by `encrypt` + + :Return: A byte string if ciphertext was a byte string or a tuple + of byte strings. A long otherwise. """ wasString=0 if not isinstance(ciphertext, types.TupleType): @@ -79,9 +95,15 @@ integers, MPZ objects, or whatever.""" else: return plaintext def sign(self, M, K): - """sign(M : string|long, K:string|long) : tuple - Return a tuple containing the signature for the message M. - K is a random parameter required by some algorithms. + """Sign a piece of data. + + :Parameter M: The piece of data to encrypt. + :Type M: byte string or long + + :Parameter K: A random parameter required by some algorithms + :Type K: byte string or long + + :Return: A tuple with two items. """ if (not self.has_private()): raise TypeError('Private key not available in this object') @@ -90,9 +112,15 @@ integers, MPZ objects, or whatever.""" return self._sign(M, K) def verify (self, M, signature): - """verify(M:string|long, signature:tuple) : bool - Verify that the signature is valid for the message M; - returns true if the signature checks out. + """Verify the validity of a signature. + + :Parameter M: The expected message. + :Type M: byte string or long + + :Parameter signature: The signature to verify. + :Type signature: tuple with two items, as return by `sign` + + :Return: True if the signature is correct, False otherwise. """ if isinstance(M, types.StringType): M=bytes_to_long(M) return self._verify(M, signature) @@ -103,8 +131,15 @@ integers, MPZ objects, or whatever.""" DeprecationWarning) def blind(self, M, B): - """blind(M : string|long, B : string|long) : string|long - Blind message M using blinding factor B. + """Blind a message to prevent certain side-channel attacks. + + :Parameter M: The message to blind. + :Type M: byte string or long + + :Parameter B: Blinding factor. + :Type B: byte string or long + + :Return: A byte string if M was so. A long otherwise. """ wasString=0 if isinstance(M, types.StringType): @@ -115,8 +150,13 @@ integers, MPZ objects, or whatever.""" else: return blindedmessage def unblind(self, M, B): - """unblind(M : string|long, B : string|long) : string|long - Unblind message M using blinding factor B. + """Unblind a message after cryptographic processing. + + :Parameter M: The encoded message to unblind. + :Type M: byte string or long + + :Parameter B: Blinding factor. + :Type B: byte string or long """ wasString=0 if isinstance(M, types.StringType): @@ -131,29 +171,35 @@ integers, MPZ objects, or whatever.""" # signature-only algorithms. They both return Boolean values # recording whether this key's algorithm can sign and encrypt. def can_sign (self): - """can_sign() : bool - Return a Boolean value recording whether this algorithm can - generate signatures. (This does not imply that this - particular key object has the private information required to - to generate a signature.) + """Tell if the algorithm can deal with cryptographic signatures. + + This property concerns the *algorithm*, not the key itself. + It may happen that this particular key object hasn't got + the private information required to generate a signature. + + :Return: boolean """ return 1 def can_encrypt (self): - """can_encrypt() : bool - Return a Boolean value recording whether this algorithm can - encrypt data. (This does not imply that this - particular key object has the private information required to - to decrypt a message.) + """Tell if the algorithm can deal with data encryption. + + This property concerns the *algorithm*, not the key itself. + It may happen that this particular key object hasn't got + the private information required to decrypt data. + + :Return: boolean """ return 1 def can_blind (self): - """can_blind() : bool - Return a Boolean value recording whether this algorithm can - blind data. (This does not imply that this - particular key object has the private information required to - to blind a message.) + """Tell if the algorithm can deal with data blinding. + + This property concerns the *algorithm*, not the key itself. + It may happen that this particular key object hasn't got + the private information required carry out blinding. + + :Return: boolean """ return 0 @@ -161,21 +207,23 @@ integers, MPZ objects, or whatever.""" # subclasses. def size (self): - """size() : int - Return the maximum number of bits that can be handled by this key. + """Tell the maximum number of bits that can be handled by this key. + + :Return: int """ return 0 def has_private (self): - """has_private() : bool - Return a Boolean denoting whether the object contains - private components. + """Tell if the key object contains private components. + + :Return: bool """ return 0 def publickey (self): - """publickey(): object - Return a new key object containing only the public information. + """Construct a new key carrying only the public information. + + :Return: A new `pubkey` object. """ return self diff --git a/lib/Crypto/PublicKey/qNEW.py b/lib/Crypto/PublicKey/qNEW.py index fc1fd9b..2a8a4b8 100644 --- a/lib/Crypto/PublicKey/qNEW.py +++ b/lib/Crypto/PublicKey/qNEW.py @@ -24,6 +24,8 @@ # =================================================================== # +"""q-NEW public-key signature algorithm.""" + __revision__ = "$Id$" from Crypto.PublicKey import pubkey diff --git a/lib/Crypto/Signature/PKCS1_PSS.py b/lib/Crypto/Signature/PKCS1_PSS.py index a89faef..4f50eb8 100644 --- a/lib/Crypto/Signature/PKCS1_PSS.py +++ b/lib/Crypto/Signature/PKCS1_PSS.py @@ -64,7 +64,7 @@ the RSA key: from __future__ import nested_scopes __revision__ = "$Id$" -__all__ = [ 'new' ] +__all__ = [ 'new', 'PSS_SigScheme' ] from Crypto.Util.py3compat import * if sys.version_info[0] == 2 and sys.version_info[1] == 1: diff --git a/lib/Crypto/Signature/PKCS1_v1_5.py b/lib/Crypto/Signature/PKCS1_v1_5.py index 5490687..73ac251 100644 --- a/lib/Crypto/Signature/PKCS1_v1_5.py +++ b/lib/Crypto/Signature/PKCS1_v1_5.py @@ -58,7 +58,7 @@ the RSA key: """ __revision__ = "$Id$" -__all__ = [ 'new' ] +__all__ = [ 'new', 'PKCS115_SigScheme' ] import Crypto.Util.number from Crypto.Util.number import ceil_div |