update windows build to Python 3.7
This commit is contained in:
parent
73105fa71e
commit
ddc59ab92d
5761 changed files with 750298 additions and 213405 deletions
|
|
@ -1,379 +1,379 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# PublicKey/DSA.py : DSA signature primitive
|
||||
#
|
||||
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
|
||||
"""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', 'DSAImplementation', '_DSAobj']
|
||||
|
||||
import sys
|
||||
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
|
||||
from Crypto.Util.py21compat import *
|
||||
|
||||
from Crypto.PublicKey import _DSA, _slowmath, pubkey
|
||||
from Crypto import Random
|
||||
|
||||
try:
|
||||
from Crypto.PublicKey import _fastmath
|
||||
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):
|
||||
self.implementation = implementation
|
||||
self.key = key
|
||||
|
||||
def __getattr__(self, attrname):
|
||||
if attrname in self.keydata:
|
||||
# For backward compatibility, allow the user to get (not set) the
|
||||
# DSA key parameters directly from this object.
|
||||
return getattr(self.key, attrname)
|
||||
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")
|
||||
|
||||
def _decrypt(self, c):
|
||||
raise TypeError("DSA cannot decrypt")
|
||||
|
||||
def _blind(self, m, r):
|
||||
raise TypeError("DSA cannot blind")
|
||||
|
||||
def _unblind(self, m, r):
|
||||
raise TypeError("DSA cannot unblind")
|
||||
|
||||
def _sign(self, m, k):
|
||||
return self.key._sign(m, k)
|
||||
|
||||
def _verify(self, m, sig):
|
||||
(r, s) = sig
|
||||
return self.key._verify(m, r, s)
|
||||
|
||||
def has_private(self):
|
||||
return self.key.has_private()
|
||||
|
||||
def size(self):
|
||||
return self.key.size()
|
||||
|
||||
def can_blind(self):
|
||||
return False
|
||||
|
||||
def can_encrypt(self):
|
||||
return False
|
||||
|
||||
def can_sign(self):
|
||||
return True
|
||||
|
||||
def publickey(self):
|
||||
return self.implementation.construct((self.key.y, self.key.g, self.key.p, self.key.q))
|
||||
|
||||
def __getstate__(self):
|
||||
d = {}
|
||||
for k in self.keydata:
|
||||
try:
|
||||
d[k] = getattr(self.key, k)
|
||||
except AttributeError:
|
||||
pass
|
||||
return d
|
||||
|
||||
def __setstate__(self, d):
|
||||
if not hasattr(self, 'implementation'):
|
||||
self.implementation = DSAImplementation()
|
||||
t = []
|
||||
for k in self.keydata:
|
||||
if k not in d:
|
||||
break
|
||||
t.append(d[k])
|
||||
self.key = self.implementation._math.dsa_construct(*tuple(t))
|
||||
|
||||
def __repr__(self):
|
||||
attrs = []
|
||||
for k in self.keydata:
|
||||
if k == 'p':
|
||||
attrs.append("p(%d)" % (self.size()+1,))
|
||||
elif hasattr(self.key, k):
|
||||
attrs.append(k)
|
||||
if self.has_private():
|
||||
attrs.append("private")
|
||||
# PY3K: This is meant to be text, do not change to bytes (data)
|
||||
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):
|
||||
"""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:
|
||||
self._math = _fastmath
|
||||
else:
|
||||
self._math = _slowmath
|
||||
|
||||
elif use_fast_math: # Explicitly select fast math
|
||||
if _fastmath is not None:
|
||||
self._math = _fastmath
|
||||
else:
|
||||
raise RuntimeError("fast math module not available")
|
||||
|
||||
else: # Explicitly select slow math
|
||||
self._math = _slowmath
|
||||
|
||||
self.error = self._math.error
|
||||
|
||||
# 'default_randfunc' parameter:
|
||||
# None (default) - use Random.new().read
|
||||
# not None - use the specified function
|
||||
self._default_randfunc = kwargs.get('default_randfunc', None)
|
||||
self._current_randfunc = None
|
||||
|
||||
def _get_randfunc(self, randfunc):
|
||||
if randfunc is not None:
|
||||
return randfunc
|
||||
elif self._current_randfunc is None:
|
||||
self._current_randfunc = Random.new().read
|
||||
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):
|
||||
if bits == 512 + 64*i:
|
||||
return self._generate(bits, randfunc, progress_func)
|
||||
|
||||
# The March 2006 draft of FIPS 186-3 also allows 2048 and 3072-bit
|
||||
# primes, but only with longer q values. Since the current DSA
|
||||
# implementation only supports a 160-bit q, we don't support larger
|
||||
# values.
|
||||
raise ValueError("Number of bits in p must be a multiple of 64 between 512 and 1024, not %d bits" % (bits,))
|
||||
|
||||
def _generate(self, bits, randfunc=None, progress_func=None):
|
||||
rf = self._get_randfunc(randfunc)
|
||||
obj = _DSA.generate_py(bits, rf, progress_func) # TODO: Don't use legacy _DSA module
|
||||
key = self._math.dsa_construct(obj.y, obj.g, obj.p, obj.q, obj.x)
|
||||
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)
|
||||
|
||||
_impl = DSAImplementation()
|
||||
generate = _impl.generate
|
||||
construct = _impl.construct
|
||||
error = _impl.error
|
||||
|
||||
# vim:set ts=4 sw=4 sts=4 expandtab:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# PublicKey/DSA.py : DSA signature primitive
|
||||
#
|
||||
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
|
||||
"""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', 'DSAImplementation', '_DSAobj']
|
||||
|
||||
import sys
|
||||
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
|
||||
from Crypto.Util.py21compat import *
|
||||
|
||||
from Crypto.PublicKey import _DSA, _slowmath, pubkey
|
||||
from Crypto import Random
|
||||
|
||||
try:
|
||||
from Crypto.PublicKey import _fastmath
|
||||
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):
|
||||
self.implementation = implementation
|
||||
self.key = key
|
||||
|
||||
def __getattr__(self, attrname):
|
||||
if attrname in self.keydata:
|
||||
# For backward compatibility, allow the user to get (not set) the
|
||||
# DSA key parameters directly from this object.
|
||||
return getattr(self.key, attrname)
|
||||
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")
|
||||
|
||||
def _decrypt(self, c):
|
||||
raise TypeError("DSA cannot decrypt")
|
||||
|
||||
def _blind(self, m, r):
|
||||
raise TypeError("DSA cannot blind")
|
||||
|
||||
def _unblind(self, m, r):
|
||||
raise TypeError("DSA cannot unblind")
|
||||
|
||||
def _sign(self, m, k):
|
||||
return self.key._sign(m, k)
|
||||
|
||||
def _verify(self, m, sig):
|
||||
(r, s) = sig
|
||||
return self.key._verify(m, r, s)
|
||||
|
||||
def has_private(self):
|
||||
return self.key.has_private()
|
||||
|
||||
def size(self):
|
||||
return self.key.size()
|
||||
|
||||
def can_blind(self):
|
||||
return False
|
||||
|
||||
def can_encrypt(self):
|
||||
return False
|
||||
|
||||
def can_sign(self):
|
||||
return True
|
||||
|
||||
def publickey(self):
|
||||
return self.implementation.construct((self.key.y, self.key.g, self.key.p, self.key.q))
|
||||
|
||||
def __getstate__(self):
|
||||
d = {}
|
||||
for k in self.keydata:
|
||||
try:
|
||||
d[k] = getattr(self.key, k)
|
||||
except AttributeError:
|
||||
pass
|
||||
return d
|
||||
|
||||
def __setstate__(self, d):
|
||||
if not hasattr(self, 'implementation'):
|
||||
self.implementation = DSAImplementation()
|
||||
t = []
|
||||
for k in self.keydata:
|
||||
if k not in d:
|
||||
break
|
||||
t.append(d[k])
|
||||
self.key = self.implementation._math.dsa_construct(*tuple(t))
|
||||
|
||||
def __repr__(self):
|
||||
attrs = []
|
||||
for k in self.keydata:
|
||||
if k == 'p':
|
||||
attrs.append("p(%d)" % (self.size()+1,))
|
||||
elif hasattr(self.key, k):
|
||||
attrs.append(k)
|
||||
if self.has_private():
|
||||
attrs.append("private")
|
||||
# PY3K: This is meant to be text, do not change to bytes (data)
|
||||
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):
|
||||
"""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:
|
||||
self._math = _fastmath
|
||||
else:
|
||||
self._math = _slowmath
|
||||
|
||||
elif use_fast_math: # Explicitly select fast math
|
||||
if _fastmath is not None:
|
||||
self._math = _fastmath
|
||||
else:
|
||||
raise RuntimeError("fast math module not available")
|
||||
|
||||
else: # Explicitly select slow math
|
||||
self._math = _slowmath
|
||||
|
||||
self.error = self._math.error
|
||||
|
||||
# 'default_randfunc' parameter:
|
||||
# None (default) - use Random.new().read
|
||||
# not None - use the specified function
|
||||
self._default_randfunc = kwargs.get('default_randfunc', None)
|
||||
self._current_randfunc = None
|
||||
|
||||
def _get_randfunc(self, randfunc):
|
||||
if randfunc is not None:
|
||||
return randfunc
|
||||
elif self._current_randfunc is None:
|
||||
self._current_randfunc = Random.new().read
|
||||
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):
|
||||
if bits == 512 + 64*i:
|
||||
return self._generate(bits, randfunc, progress_func)
|
||||
|
||||
# The March 2006 draft of FIPS 186-3 also allows 2048 and 3072-bit
|
||||
# primes, but only with longer q values. Since the current DSA
|
||||
# implementation only supports a 160-bit q, we don't support larger
|
||||
# values.
|
||||
raise ValueError("Number of bits in p must be a multiple of 64 between 512 and 1024, not %d bits" % (bits,))
|
||||
|
||||
def _generate(self, bits, randfunc=None, progress_func=None):
|
||||
rf = self._get_randfunc(randfunc)
|
||||
obj = _DSA.generate_py(bits, rf, progress_func) # TODO: Don't use legacy _DSA module
|
||||
key = self._math.dsa_construct(obj.y, obj.g, obj.p, obj.q, obj.x)
|
||||
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)
|
||||
|
||||
_impl = DSAImplementation()
|
||||
generate = _impl.generate
|
||||
construct = _impl.construct
|
||||
error = _impl.error
|
||||
|
||||
# vim:set ts=4 sw=4 sts=4 expandtab:
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,115 +1,115 @@
|
|||
|
||||
#
|
||||
# DSA.py : Digital Signature Algorithm
|
||||
#
|
||||
# Part of the Python Cryptography Toolkit
|
||||
#
|
||||
# Written by Andrew Kuchling, Paul Swartz, and others
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
#
|
||||
|
||||
__revision__ = "$Id$"
|
||||
|
||||
from Crypto.PublicKey.pubkey import *
|
||||
from Crypto.Util import number
|
||||
from Crypto.Util.number import bytes_to_long, long_to_bytes
|
||||
from Crypto.Hash import SHA
|
||||
from Crypto.Util.py3compat import *
|
||||
|
||||
class error (Exception):
|
||||
pass
|
||||
|
||||
def generateQ(randfunc):
|
||||
S=randfunc(20)
|
||||
hash1=SHA.new(S).digest()
|
||||
hash2=SHA.new(long_to_bytes(bytes_to_long(S)+1)).digest()
|
||||
q = bignum(0)
|
||||
for i in range(0,20):
|
||||
c=bord(hash1[i])^bord(hash2[i])
|
||||
if i==0:
|
||||
c=c | 128
|
||||
if i==19:
|
||||
c= c | 1
|
||||
q=q*256+c
|
||||
while (not isPrime(q)):
|
||||
q=q+2
|
||||
if pow(2,159) < q < pow(2,160):
|
||||
return S, q
|
||||
raise RuntimeError('Bad q value generated')
|
||||
|
||||
def generate_py(bits, randfunc, progress_func=None):
|
||||
"""generate(bits:int, randfunc:callable, progress_func:callable)
|
||||
|
||||
Generate a DSA key of length 'bits', using 'randfunc' to get
|
||||
random data and 'progress_func', if present, to display
|
||||
the progress of the key generation.
|
||||
"""
|
||||
|
||||
if bits<160:
|
||||
raise ValueError('Key length < 160 bits')
|
||||
obj=DSAobj()
|
||||
# Generate string S and prime q
|
||||
if progress_func:
|
||||
progress_func('p,q\n')
|
||||
while (1):
|
||||
S, obj.q = generateQ(randfunc)
|
||||
n=divmod(bits-1, 160)[0]
|
||||
C, N, V = 0, 2, {}
|
||||
b=(obj.q >> 5) & 15
|
||||
powb=pow(bignum(2), b)
|
||||
powL1=pow(bignum(2), bits-1)
|
||||
while C<4096:
|
||||
for k in range(0, n+1):
|
||||
V[k]=bytes_to_long(SHA.new(S+bstr(N)+bstr(k)).digest())
|
||||
W=V[n] % powb
|
||||
for k in range(n-1, -1, -1):
|
||||
W=(W<<160)+V[k]
|
||||
X=W+powL1
|
||||
p=X-(X%(2*obj.q)-1)
|
||||
if powL1<=p and isPrime(p):
|
||||
break
|
||||
C, N = C+1, N+n+1
|
||||
if C<4096:
|
||||
break
|
||||
if progress_func:
|
||||
progress_func('4096 multiples failed\n')
|
||||
|
||||
obj.p = p
|
||||
power=divmod(p-1, obj.q)[0]
|
||||
if progress_func:
|
||||
progress_func('h,g\n')
|
||||
while (1):
|
||||
h=bytes_to_long(randfunc(bits)) % (p-1)
|
||||
g=pow(h, power, p)
|
||||
if 1<h<p-1 and g>1:
|
||||
break
|
||||
obj.g=g
|
||||
if progress_func:
|
||||
progress_func('x,y\n')
|
||||
while (1):
|
||||
x=bytes_to_long(randfunc(20))
|
||||
if 0 < x < obj.q:
|
||||
break
|
||||
obj.x, obj.y = x, pow(g, x, p)
|
||||
return obj
|
||||
|
||||
class DSAobj:
|
||||
pass
|
||||
|
||||
|
||||
#
|
||||
# DSA.py : Digital Signature Algorithm
|
||||
#
|
||||
# Part of the Python Cryptography Toolkit
|
||||
#
|
||||
# Written by Andrew Kuchling, Paul Swartz, and others
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
#
|
||||
|
||||
__revision__ = "$Id$"
|
||||
|
||||
from Crypto.PublicKey.pubkey import *
|
||||
from Crypto.Util import number
|
||||
from Crypto.Util.number import bytes_to_long, long_to_bytes
|
||||
from Crypto.Hash import SHA
|
||||
from Crypto.Util.py3compat import *
|
||||
|
||||
class error (Exception):
|
||||
pass
|
||||
|
||||
def generateQ(randfunc):
|
||||
S=randfunc(20)
|
||||
hash1=SHA.new(S).digest()
|
||||
hash2=SHA.new(long_to_bytes(bytes_to_long(S)+1)).digest()
|
||||
q = bignum(0)
|
||||
for i in range(0,20):
|
||||
c=bord(hash1[i])^bord(hash2[i])
|
||||
if i==0:
|
||||
c=c | 128
|
||||
if i==19:
|
||||
c= c | 1
|
||||
q=q*256+c
|
||||
while (not isPrime(q)):
|
||||
q=q+2
|
||||
if pow(2,159) < q < pow(2,160):
|
||||
return S, q
|
||||
raise RuntimeError('Bad q value generated')
|
||||
|
||||
def generate_py(bits, randfunc, progress_func=None):
|
||||
"""generate(bits:int, randfunc:callable, progress_func:callable)
|
||||
|
||||
Generate a DSA key of length 'bits', using 'randfunc' to get
|
||||
random data and 'progress_func', if present, to display
|
||||
the progress of the key generation.
|
||||
"""
|
||||
|
||||
if bits<160:
|
||||
raise ValueError('Key length < 160 bits')
|
||||
obj=DSAobj()
|
||||
# Generate string S and prime q
|
||||
if progress_func:
|
||||
progress_func('p,q\n')
|
||||
while (1):
|
||||
S, obj.q = generateQ(randfunc)
|
||||
n=divmod(bits-1, 160)[0]
|
||||
C, N, V = 0, 2, {}
|
||||
b=(obj.q >> 5) & 15
|
||||
powb=pow(bignum(2), b)
|
||||
powL1=pow(bignum(2), bits-1)
|
||||
while C<4096:
|
||||
for k in range(0, n+1):
|
||||
V[k]=bytes_to_long(SHA.new(S+bstr(N)+bstr(k)).digest())
|
||||
W=V[n] % powb
|
||||
for k in range(n-1, -1, -1):
|
||||
W=(W<<160)+V[k]
|
||||
X=W+powL1
|
||||
p=X-(X%(2*obj.q)-1)
|
||||
if powL1<=p and isPrime(p):
|
||||
break
|
||||
C, N = C+1, N+n+1
|
||||
if C<4096:
|
||||
break
|
||||
if progress_func:
|
||||
progress_func('4096 multiples failed\n')
|
||||
|
||||
obj.p = p
|
||||
power=divmod(p-1, obj.q)[0]
|
||||
if progress_func:
|
||||
progress_func('h,g\n')
|
||||
while (1):
|
||||
h=bytes_to_long(randfunc(bits)) % (p-1)
|
||||
g=pow(h, power, p)
|
||||
if 1<h<p-1 and g>1:
|
||||
break
|
||||
obj.g=g
|
||||
if progress_func:
|
||||
progress_func('x,y\n')
|
||||
while (1):
|
||||
x=bytes_to_long(randfunc(20))
|
||||
if 0 < x < obj.q:
|
||||
break
|
||||
obj.x, obj.y = x, pow(g, x, p)
|
||||
return obj
|
||||
|
||||
class DSAobj:
|
||||
pass
|
||||
|
||||
|
|
|
|||
|
|
@ -1,81 +1,81 @@
|
|||
#
|
||||
# RSA.py : RSA encryption/decryption
|
||||
#
|
||||
# Part of the Python Cryptography Toolkit
|
||||
#
|
||||
# Written by Andrew Kuchling, Paul Swartz, and others
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
#
|
||||
|
||||
__revision__ = "$Id$"
|
||||
|
||||
from Crypto.PublicKey import pubkey
|
||||
from Crypto.Util import number
|
||||
|
||||
def generate_py(bits, randfunc, progress_func=None, e=65537):
|
||||
"""generate(bits:int, randfunc:callable, progress_func:callable, e:int)
|
||||
|
||||
Generate an RSA key of length 'bits', public exponent 'e'(which must be
|
||||
odd), using 'randfunc' to get random data and 'progress_func',
|
||||
if present, to display the progress of the key generation.
|
||||
"""
|
||||
obj=RSAobj()
|
||||
obj.e = int(e)
|
||||
|
||||
# Generate the prime factors of n
|
||||
if progress_func:
|
||||
progress_func('p,q\n')
|
||||
p = q = 1
|
||||
while number.size(p*q) < bits:
|
||||
# Note that q might be one bit longer than p if somebody specifies an odd
|
||||
# number of bits for the key. (Why would anyone do that? You don't get
|
||||
# more security.)
|
||||
p = pubkey.getStrongPrime(bits>>1, obj.e, 1e-12, randfunc)
|
||||
q = pubkey.getStrongPrime(bits - (bits>>1), obj.e, 1e-12, randfunc)
|
||||
|
||||
# It's OK for p to be larger than q, but let's be
|
||||
# kind to the function that will invert it for
|
||||
# th calculation of u.
|
||||
if p > q:
|
||||
(p, q)=(q, p)
|
||||
obj.p = p
|
||||
obj.q = q
|
||||
|
||||
if progress_func:
|
||||
progress_func('u\n')
|
||||
obj.u = pubkey.inverse(obj.p, obj.q)
|
||||
obj.n = obj.p*obj.q
|
||||
|
||||
if progress_func:
|
||||
progress_func('d\n')
|
||||
obj.d=pubkey.inverse(obj.e, (obj.p-1)*(obj.q-1))
|
||||
|
||||
assert bits <= 1+obj.size(), "Generated key is too small"
|
||||
|
||||
return obj
|
||||
|
||||
class RSAobj(pubkey.pubkey):
|
||||
|
||||
def size(self):
|
||||
"""size() : int
|
||||
Return the maximum number of bits that can be handled by this key.
|
||||
"""
|
||||
return number.size(self.n) - 1
|
||||
|
||||
#
|
||||
# RSA.py : RSA encryption/decryption
|
||||
#
|
||||
# Part of the Python Cryptography Toolkit
|
||||
#
|
||||
# Written by Andrew Kuchling, Paul Swartz, and others
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
#
|
||||
|
||||
__revision__ = "$Id$"
|
||||
|
||||
from Crypto.PublicKey import pubkey
|
||||
from Crypto.Util import number
|
||||
|
||||
def generate_py(bits, randfunc, progress_func=None, e=65537):
|
||||
"""generate(bits:int, randfunc:callable, progress_func:callable, e:int)
|
||||
|
||||
Generate an RSA key of length 'bits', public exponent 'e'(which must be
|
||||
odd), using 'randfunc' to get random data and 'progress_func',
|
||||
if present, to display the progress of the key generation.
|
||||
"""
|
||||
obj=RSAobj()
|
||||
obj.e = int(e)
|
||||
|
||||
# Generate the prime factors of n
|
||||
if progress_func:
|
||||
progress_func('p,q\n')
|
||||
p = q = 1
|
||||
while number.size(p*q) < bits:
|
||||
# Note that q might be one bit longer than p if somebody specifies an odd
|
||||
# number of bits for the key. (Why would anyone do that? You don't get
|
||||
# more security.)
|
||||
p = pubkey.getStrongPrime(bits>>1, obj.e, 1e-12, randfunc)
|
||||
q = pubkey.getStrongPrime(bits - (bits>>1), obj.e, 1e-12, randfunc)
|
||||
|
||||
# It's OK for p to be larger than q, but let's be
|
||||
# kind to the function that will invert it for
|
||||
# th calculation of u.
|
||||
if p > q:
|
||||
(p, q)=(q, p)
|
||||
obj.p = p
|
||||
obj.q = q
|
||||
|
||||
if progress_func:
|
||||
progress_func('u\n')
|
||||
obj.u = pubkey.inverse(obj.p, obj.q)
|
||||
obj.n = obj.p*obj.q
|
||||
|
||||
if progress_func:
|
||||
progress_func('d\n')
|
||||
obj.d=pubkey.inverse(obj.e, (obj.p-1)*(obj.q-1))
|
||||
|
||||
assert bits <= 1+obj.size(), "Generated key is too small"
|
||||
|
||||
return obj
|
||||
|
||||
class RSAobj(pubkey.pubkey):
|
||||
|
||||
def size(self):
|
||||
"""size() : int
|
||||
Return the maximum number of bits that can be handled by this key.
|
||||
"""
|
||||
return number.size(self.n) - 1
|
||||
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -1,187 +1,187 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# PubKey/RSA/_slowmath.py : Pure Python implementation of the RSA portions of _fastmath
|
||||
#
|
||||
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
|
||||
"""Pure Python implementation of the RSA-related portions of Crypto.PublicKey._fastmath."""
|
||||
|
||||
__revision__ = "$Id$"
|
||||
|
||||
__all__ = ['rsa_construct']
|
||||
|
||||
import sys
|
||||
|
||||
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
|
||||
from Crypto.Util.py21compat import *
|
||||
from Crypto.Util.number import size, inverse, GCD
|
||||
|
||||
class error(Exception):
|
||||
pass
|
||||
|
||||
class _RSAKey(object):
|
||||
def _blind(self, m, r):
|
||||
# compute r**e * m (mod n)
|
||||
return m * pow(r, self.e, self.n)
|
||||
|
||||
def _unblind(self, m, r):
|
||||
# compute m / r (mod n)
|
||||
return inverse(r, self.n) * m % self.n
|
||||
|
||||
def _decrypt(self, c):
|
||||
# compute c**d (mod n)
|
||||
if not self.has_private():
|
||||
raise TypeError("No private key")
|
||||
if (hasattr(self,'p') and hasattr(self,'q') and hasattr(self,'u')):
|
||||
m1 = pow(c, self.d % (self.p-1), self.p)
|
||||
m2 = pow(c, self.d % (self.q-1), self.q)
|
||||
h = m2 - m1
|
||||
if (h<0):
|
||||
h = h + self.q
|
||||
h = h*self.u % self.q
|
||||
return h*self.p+m1
|
||||
return pow(c, self.d, self.n)
|
||||
|
||||
def _encrypt(self, m):
|
||||
# compute m**d (mod n)
|
||||
return pow(m, self.e, self.n)
|
||||
|
||||
def _sign(self, m): # alias for _decrypt
|
||||
if not self.has_private():
|
||||
raise TypeError("No private key")
|
||||
return self._decrypt(m)
|
||||
|
||||
def _verify(self, m, sig):
|
||||
return self._encrypt(sig) == m
|
||||
|
||||
def has_private(self):
|
||||
return hasattr(self, 'd')
|
||||
|
||||
def size(self):
|
||||
"""Return the maximum number of bits that can be encrypted"""
|
||||
return size(self.n) - 1
|
||||
|
||||
def rsa_construct(n, e, d=None, p=None, q=None, u=None):
|
||||
"""Construct an RSAKey object"""
|
||||
assert isinstance(n, int)
|
||||
assert isinstance(e, int)
|
||||
assert isinstance(d, (int, type(None)))
|
||||
assert isinstance(p, (int, type(None)))
|
||||
assert isinstance(q, (int, type(None)))
|
||||
assert isinstance(u, (int, type(None)))
|
||||
obj = _RSAKey()
|
||||
obj.n = n
|
||||
obj.e = e
|
||||
if d is None:
|
||||
return obj
|
||||
obj.d = d
|
||||
if p is not None and q is not None:
|
||||
obj.p = p
|
||||
obj.q = q
|
||||
else:
|
||||
# Compute factors p and q from the private exponent d.
|
||||
# We assume that n has no more than two factors.
|
||||
# See 8.2.2(i) in Handbook of Applied Cryptography.
|
||||
ktot = d*e-1
|
||||
# The quantity d*e-1 is a multiple of phi(n), even,
|
||||
# and can be represented as t*2^s.
|
||||
t = ktot
|
||||
while t%2==0:
|
||||
t=divmod(t,2)[0]
|
||||
# Cycle through all multiplicative inverses in Zn.
|
||||
# The algorithm is non-deterministic, but there is a 50% chance
|
||||
# any candidate a leads to successful factoring.
|
||||
# See "Digitalized Signatures and Public Key Functions as Intractable
|
||||
# as Factorization", M. Rabin, 1979
|
||||
spotted = 0
|
||||
a = 2
|
||||
while not spotted and a<100:
|
||||
k = t
|
||||
# Cycle through all values a^{t*2^i}=a^k
|
||||
while k<ktot:
|
||||
cand = pow(a,k,n)
|
||||
# Check if a^k is a non-trivial root of unity (mod n)
|
||||
if cand!=1 and cand!=(n-1) and pow(cand,2,n)==1:
|
||||
# We have found a number such that (cand-1)(cand+1)=0 (mod n).
|
||||
# Either of the terms divides n.
|
||||
obj.p = GCD(cand+1,n)
|
||||
spotted = 1
|
||||
break
|
||||
k = k*2
|
||||
# This value was not any good... let's try another!
|
||||
a = a+2
|
||||
if not spotted:
|
||||
raise ValueError("Unable to compute factors p and q from exponent d.")
|
||||
# Found !
|
||||
assert ((n % obj.p)==0)
|
||||
obj.q = divmod(n,obj.p)[0]
|
||||
if u is not None:
|
||||
obj.u = u
|
||||
else:
|
||||
obj.u = inverse(obj.p, obj.q)
|
||||
return obj
|
||||
|
||||
class _DSAKey(object):
|
||||
def size(self):
|
||||
"""Return the maximum number of bits that can be encrypted"""
|
||||
return size(self.p) - 1
|
||||
|
||||
def has_private(self):
|
||||
return hasattr(self, 'x')
|
||||
|
||||
def _sign(self, m, k): # alias for _decrypt
|
||||
# SECURITY TODO - We _should_ be computing SHA1(m), but we don't because that's the API.
|
||||
if not self.has_private():
|
||||
raise TypeError("No private key")
|
||||
if not (1 < k < self.q):
|
||||
raise ValueError("k is not between 2 and q-1")
|
||||
inv_k = inverse(k, self.q) # Compute k**-1 mod q
|
||||
r = pow(self.g, k, self.p) % self.q # r = (g**k mod p) mod q
|
||||
s = (inv_k * (m + self.x * r)) % self.q
|
||||
return (r, s)
|
||||
|
||||
def _verify(self, m, r, s):
|
||||
# SECURITY TODO - We _should_ be computing SHA1(m), but we don't because that's the API.
|
||||
if not (0 < r < self.q) or not (0 < s < self.q):
|
||||
return False
|
||||
w = inverse(s, self.q)
|
||||
u1 = (m*w) % self.q
|
||||
u2 = (r*w) % self.q
|
||||
v = (pow(self.g, u1, self.p) * pow(self.y, u2, self.p) % self.p) % self.q
|
||||
return v == r
|
||||
|
||||
def dsa_construct(y, g, p, q, x=None):
|
||||
assert isinstance(y, int)
|
||||
assert isinstance(g, int)
|
||||
assert isinstance(p, int)
|
||||
assert isinstance(q, int)
|
||||
assert isinstance(x, (int, type(None)))
|
||||
obj = _DSAKey()
|
||||
obj.y = y
|
||||
obj.g = g
|
||||
obj.p = p
|
||||
obj.q = q
|
||||
if x is not None: obj.x = x
|
||||
return obj
|
||||
|
||||
|
||||
# vim:set ts=4 sw=4 sts=4 expandtab:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# PubKey/RSA/_slowmath.py : Pure Python implementation of the RSA portions of _fastmath
|
||||
#
|
||||
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
|
||||
"""Pure Python implementation of the RSA-related portions of Crypto.PublicKey._fastmath."""
|
||||
|
||||
__revision__ = "$Id$"
|
||||
|
||||
__all__ = ['rsa_construct']
|
||||
|
||||
import sys
|
||||
|
||||
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
|
||||
from Crypto.Util.py21compat import *
|
||||
from Crypto.Util.number import size, inverse, GCD
|
||||
|
||||
class error(Exception):
|
||||
pass
|
||||
|
||||
class _RSAKey(object):
|
||||
def _blind(self, m, r):
|
||||
# compute r**e * m (mod n)
|
||||
return m * pow(r, self.e, self.n)
|
||||
|
||||
def _unblind(self, m, r):
|
||||
# compute m / r (mod n)
|
||||
return inverse(r, self.n) * m % self.n
|
||||
|
||||
def _decrypt(self, c):
|
||||
# compute c**d (mod n)
|
||||
if not self.has_private():
|
||||
raise TypeError("No private key")
|
||||
if (hasattr(self,'p') and hasattr(self,'q') and hasattr(self,'u')):
|
||||
m1 = pow(c, self.d % (self.p-1), self.p)
|
||||
m2 = pow(c, self.d % (self.q-1), self.q)
|
||||
h = m2 - m1
|
||||
if (h<0):
|
||||
h = h + self.q
|
||||
h = h*self.u % self.q
|
||||
return h*self.p+m1
|
||||
return pow(c, self.d, self.n)
|
||||
|
||||
def _encrypt(self, m):
|
||||
# compute m**d (mod n)
|
||||
return pow(m, self.e, self.n)
|
||||
|
||||
def _sign(self, m): # alias for _decrypt
|
||||
if not self.has_private():
|
||||
raise TypeError("No private key")
|
||||
return self._decrypt(m)
|
||||
|
||||
def _verify(self, m, sig):
|
||||
return self._encrypt(sig) == m
|
||||
|
||||
def has_private(self):
|
||||
return hasattr(self, 'd')
|
||||
|
||||
def size(self):
|
||||
"""Return the maximum number of bits that can be encrypted"""
|
||||
return size(self.n) - 1
|
||||
|
||||
def rsa_construct(n, e, d=None, p=None, q=None, u=None):
|
||||
"""Construct an RSAKey object"""
|
||||
assert isinstance(n, int)
|
||||
assert isinstance(e, int)
|
||||
assert isinstance(d, (int, type(None)))
|
||||
assert isinstance(p, (int, type(None)))
|
||||
assert isinstance(q, (int, type(None)))
|
||||
assert isinstance(u, (int, type(None)))
|
||||
obj = _RSAKey()
|
||||
obj.n = n
|
||||
obj.e = e
|
||||
if d is None:
|
||||
return obj
|
||||
obj.d = d
|
||||
if p is not None and q is not None:
|
||||
obj.p = p
|
||||
obj.q = q
|
||||
else:
|
||||
# Compute factors p and q from the private exponent d.
|
||||
# We assume that n has no more than two factors.
|
||||
# See 8.2.2(i) in Handbook of Applied Cryptography.
|
||||
ktot = d*e-1
|
||||
# The quantity d*e-1 is a multiple of phi(n), even,
|
||||
# and can be represented as t*2^s.
|
||||
t = ktot
|
||||
while t%2==0:
|
||||
t=divmod(t,2)[0]
|
||||
# Cycle through all multiplicative inverses in Zn.
|
||||
# The algorithm is non-deterministic, but there is a 50% chance
|
||||
# any candidate a leads to successful factoring.
|
||||
# See "Digitalized Signatures and Public Key Functions as Intractable
|
||||
# as Factorization", M. Rabin, 1979
|
||||
spotted = 0
|
||||
a = 2
|
||||
while not spotted and a<100:
|
||||
k = t
|
||||
# Cycle through all values a^{t*2^i}=a^k
|
||||
while k<ktot:
|
||||
cand = pow(a,k,n)
|
||||
# Check if a^k is a non-trivial root of unity (mod n)
|
||||
if cand!=1 and cand!=(n-1) and pow(cand,2,n)==1:
|
||||
# We have found a number such that (cand-1)(cand+1)=0 (mod n).
|
||||
# Either of the terms divides n.
|
||||
obj.p = GCD(cand+1,n)
|
||||
spotted = 1
|
||||
break
|
||||
k = k*2
|
||||
# This value was not any good... let's try another!
|
||||
a = a+2
|
||||
if not spotted:
|
||||
raise ValueError("Unable to compute factors p and q from exponent d.")
|
||||
# Found !
|
||||
assert ((n % obj.p)==0)
|
||||
obj.q = divmod(n,obj.p)[0]
|
||||
if u is not None:
|
||||
obj.u = u
|
||||
else:
|
||||
obj.u = inverse(obj.p, obj.q)
|
||||
return obj
|
||||
|
||||
class _DSAKey(object):
|
||||
def size(self):
|
||||
"""Return the maximum number of bits that can be encrypted"""
|
||||
return size(self.p) - 1
|
||||
|
||||
def has_private(self):
|
||||
return hasattr(self, 'x')
|
||||
|
||||
def _sign(self, m, k): # alias for _decrypt
|
||||
# SECURITY TODO - We _should_ be computing SHA1(m), but we don't because that's the API.
|
||||
if not self.has_private():
|
||||
raise TypeError("No private key")
|
||||
if not (1 < k < self.q):
|
||||
raise ValueError("k is not between 2 and q-1")
|
||||
inv_k = inverse(k, self.q) # Compute k**-1 mod q
|
||||
r = pow(self.g, k, self.p) % self.q # r = (g**k mod p) mod q
|
||||
s = (inv_k * (m + self.x * r)) % self.q
|
||||
return (r, s)
|
||||
|
||||
def _verify(self, m, r, s):
|
||||
# SECURITY TODO - We _should_ be computing SHA1(m), but we don't because that's the API.
|
||||
if not (0 < r < self.q) or not (0 < s < self.q):
|
||||
return False
|
||||
w = inverse(s, self.q)
|
||||
u1 = (m*w) % self.q
|
||||
u2 = (r*w) % self.q
|
||||
v = (pow(self.g, u1, self.p) * pow(self.y, u2, self.p) % self.p) % self.q
|
||||
return v == r
|
||||
|
||||
def dsa_construct(y, g, p, q, x=None):
|
||||
assert isinstance(y, int)
|
||||
assert isinstance(g, int)
|
||||
assert isinstance(p, int)
|
||||
assert isinstance(q, int)
|
||||
assert isinstance(x, (int, type(None)))
|
||||
obj = _DSAKey()
|
||||
obj.y = y
|
||||
obj.g = g
|
||||
obj.p = p
|
||||
obj.q = q
|
||||
if x is not None: obj.x = x
|
||||
return obj
|
||||
|
||||
|
||||
# vim:set ts=4 sw=4 sts=4 expandtab:
|
||||
|
||||
|
|
|
|||
|
|
@ -1,240 +1,240 @@
|
|||
#
|
||||
# pubkey.py : Internal functions for public key operations
|
||||
#
|
||||
# Part of the Python Cryptography Toolkit
|
||||
#
|
||||
# Written by Andrew Kuchling, Paul Swartz, and others
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
#
|
||||
|
||||
__revision__ = "$Id$"
|
||||
|
||||
import types, warnings
|
||||
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
|
||||
|
||||
def __getstate__(self):
|
||||
"""To keep key objects platform-independent, the key data is
|
||||
converted to standard Python long integers before being
|
||||
written out. It will then be reconverted as necessary on
|
||||
restoration."""
|
||||
d=self.__dict__
|
||||
for key in self.keydata:
|
||||
if key in d: d[key]=int(d[key])
|
||||
return d
|
||||
|
||||
def __setstate__(self, d):
|
||||
"""On unpickling a key object, the key data is converted to the big
|
||||
number representation being used, whether that is Python long
|
||||
integers, MPZ objects, or whatever."""
|
||||
for key in self.keydata:
|
||||
if key in d: self.__dict__[key]=bignum(d[key])
|
||||
|
||||
def encrypt(self, plaintext, K):
|
||||
"""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, bytes):
|
||||
plaintext=bytes_to_long(plaintext) ; wasString=1
|
||||
if isinstance(K, bytes):
|
||||
K=bytes_to_long(K)
|
||||
ciphertext=self._encrypt(plaintext, K)
|
||||
if wasString: return tuple(map(long_to_bytes, ciphertext))
|
||||
else: return ciphertext
|
||||
|
||||
def decrypt(self, ciphertext):
|
||||
"""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, tuple):
|
||||
ciphertext=(ciphertext,)
|
||||
if isinstance(ciphertext[0], bytes):
|
||||
ciphertext=tuple(map(bytes_to_long, ciphertext)) ; wasString=1
|
||||
plaintext=self._decrypt(ciphertext)
|
||||
if wasString: return long_to_bytes(plaintext)
|
||||
else: return plaintext
|
||||
|
||||
def sign(self, M, K):
|
||||
"""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')
|
||||
if isinstance(M, bytes): M=bytes_to_long(M)
|
||||
if isinstance(K, bytes): K=bytes_to_long(K)
|
||||
return self._sign(M, K)
|
||||
|
||||
def verify (self, M, signature):
|
||||
"""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, bytes): M=bytes_to_long(M)
|
||||
return self._verify(M, signature)
|
||||
|
||||
# alias to compensate for the old validate() name
|
||||
def validate (self, M, signature):
|
||||
warnings.warn("validate() method name is obsolete; use verify()",
|
||||
DeprecationWarning)
|
||||
|
||||
def blind(self, M, 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, bytes):
|
||||
M=bytes_to_long(M) ; wasString=1
|
||||
if isinstance(B, bytes): B=bytes_to_long(B)
|
||||
blindedmessage=self._blind(M, B)
|
||||
if wasString: return long_to_bytes(blindedmessage)
|
||||
else: return blindedmessage
|
||||
|
||||
def unblind(self, M, 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, bytes):
|
||||
M=bytes_to_long(M) ; wasString=1
|
||||
if isinstance(B, bytes): B=bytes_to_long(B)
|
||||
unblindedmessage=self._unblind(M, B)
|
||||
if wasString: return long_to_bytes(unblindedmessage)
|
||||
else: return unblindedmessage
|
||||
|
||||
|
||||
# The following methods will usually be left alone, except for
|
||||
# signature-only algorithms. They both return Boolean values
|
||||
# recording whether this key's algorithm can sign and encrypt.
|
||||
def can_sign (self):
|
||||
"""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):
|
||||
"""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):
|
||||
"""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
|
||||
|
||||
# The following methods will certainly be overridden by
|
||||
# subclasses.
|
||||
|
||||
def size (self):
|
||||
"""Tell the maximum number of bits that can be handled by this key.
|
||||
|
||||
:Return: int
|
||||
"""
|
||||
return 0
|
||||
|
||||
def has_private (self):
|
||||
"""Tell if the key object contains private components.
|
||||
|
||||
:Return: bool
|
||||
"""
|
||||
return 0
|
||||
|
||||
def publickey (self):
|
||||
"""Construct a new key carrying only the public information.
|
||||
|
||||
:Return: A new `pubkey` object.
|
||||
"""
|
||||
return self
|
||||
|
||||
def __eq__ (self, other):
|
||||
"""__eq__(other): 0, 1
|
||||
Compare us to other for equality.
|
||||
"""
|
||||
return self.__getstate__() == other.__getstate__()
|
||||
|
||||
def __ne__ (self, other):
|
||||
"""__ne__(other): 0, 1
|
||||
Compare us to other for inequality.
|
||||
"""
|
||||
return not self.__eq__(other)
|
||||
#
|
||||
# pubkey.py : Internal functions for public key operations
|
||||
#
|
||||
# Part of the Python Cryptography Toolkit
|
||||
#
|
||||
# Written by Andrew Kuchling, Paul Swartz, and others
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
#
|
||||
|
||||
__revision__ = "$Id$"
|
||||
|
||||
import types, warnings
|
||||
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
|
||||
|
||||
def __getstate__(self):
|
||||
"""To keep key objects platform-independent, the key data is
|
||||
converted to standard Python long integers before being
|
||||
written out. It will then be reconverted as necessary on
|
||||
restoration."""
|
||||
d=self.__dict__
|
||||
for key in self.keydata:
|
||||
if key in d: d[key]=int(d[key])
|
||||
return d
|
||||
|
||||
def __setstate__(self, d):
|
||||
"""On unpickling a key object, the key data is converted to the big
|
||||
number representation being used, whether that is Python long
|
||||
integers, MPZ objects, or whatever."""
|
||||
for key in self.keydata:
|
||||
if key in d: self.__dict__[key]=bignum(d[key])
|
||||
|
||||
def encrypt(self, plaintext, K):
|
||||
"""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, bytes):
|
||||
plaintext=bytes_to_long(plaintext) ; wasString=1
|
||||
if isinstance(K, bytes):
|
||||
K=bytes_to_long(K)
|
||||
ciphertext=self._encrypt(plaintext, K)
|
||||
if wasString: return tuple(map(long_to_bytes, ciphertext))
|
||||
else: return ciphertext
|
||||
|
||||
def decrypt(self, ciphertext):
|
||||
"""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, tuple):
|
||||
ciphertext=(ciphertext,)
|
||||
if isinstance(ciphertext[0], bytes):
|
||||
ciphertext=tuple(map(bytes_to_long, ciphertext)) ; wasString=1
|
||||
plaintext=self._decrypt(ciphertext)
|
||||
if wasString: return long_to_bytes(plaintext)
|
||||
else: return plaintext
|
||||
|
||||
def sign(self, M, K):
|
||||
"""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')
|
||||
if isinstance(M, bytes): M=bytes_to_long(M)
|
||||
if isinstance(K, bytes): K=bytes_to_long(K)
|
||||
return self._sign(M, K)
|
||||
|
||||
def verify (self, M, signature):
|
||||
"""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, bytes): M=bytes_to_long(M)
|
||||
return self._verify(M, signature)
|
||||
|
||||
# alias to compensate for the old validate() name
|
||||
def validate (self, M, signature):
|
||||
warnings.warn("validate() method name is obsolete; use verify()",
|
||||
DeprecationWarning)
|
||||
|
||||
def blind(self, M, 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, bytes):
|
||||
M=bytes_to_long(M) ; wasString=1
|
||||
if isinstance(B, bytes): B=bytes_to_long(B)
|
||||
blindedmessage=self._blind(M, B)
|
||||
if wasString: return long_to_bytes(blindedmessage)
|
||||
else: return blindedmessage
|
||||
|
||||
def unblind(self, M, 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, bytes):
|
||||
M=bytes_to_long(M) ; wasString=1
|
||||
if isinstance(B, bytes): B=bytes_to_long(B)
|
||||
unblindedmessage=self._unblind(M, B)
|
||||
if wasString: return long_to_bytes(unblindedmessage)
|
||||
else: return unblindedmessage
|
||||
|
||||
|
||||
# The following methods will usually be left alone, except for
|
||||
# signature-only algorithms. They both return Boolean values
|
||||
# recording whether this key's algorithm can sign and encrypt.
|
||||
def can_sign (self):
|
||||
"""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):
|
||||
"""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):
|
||||
"""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
|
||||
|
||||
# The following methods will certainly be overridden by
|
||||
# subclasses.
|
||||
|
||||
def size (self):
|
||||
"""Tell the maximum number of bits that can be handled by this key.
|
||||
|
||||
:Return: int
|
||||
"""
|
||||
return 0
|
||||
|
||||
def has_private (self):
|
||||
"""Tell if the key object contains private components.
|
||||
|
||||
:Return: bool
|
||||
"""
|
||||
return 0
|
||||
|
||||
def publickey (self):
|
||||
"""Construct a new key carrying only the public information.
|
||||
|
||||
:Return: A new `pubkey` object.
|
||||
"""
|
||||
return self
|
||||
|
||||
def __eq__ (self, other):
|
||||
"""__eq__(other): 0, 1
|
||||
Compare us to other for equality.
|
||||
"""
|
||||
return self.__getstate__() == other.__getstate__()
|
||||
|
||||
def __ne__ (self, other):
|
||||
"""__ne__(other): 0, 1
|
||||
Compare us to other for inequality.
|
||||
"""
|
||||
return not self.__eq__(other)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue