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 = long(e)
# Generate the prime factors of n
if progress_func:
progress_func('p,q\n')
p = q = 1L
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
python类size()的实例源码
def size(self):
"""size() : int
Return the maximum number of bits that can be handled by this key.
"""
return number.size(self.n) - 1
def randrange(self, *args):
"""randrange([start,] stop[, step]):
Return a randomly-selected element from range(start, stop, step)."""
if len(args) == 3:
(start, stop, step) = args
elif len(args) == 2:
(start, stop) = args
step = 1
elif len(args) == 1:
(stop,) = args
start = 0
step = 1
else:
raise TypeError("randrange expected at most 3 arguments, got %d" % (len(args),))
if (not isinstance(start, (int, long))
or not isinstance(stop, (int, long))
or not isinstance(step, (int, long))):
raise TypeError("randrange requires integer arguments")
if step == 0:
raise ValueError("randrange step argument must not be zero")
num_choices = ceil_div(stop - start, step)
if num_choices < 0:
num_choices = 0
if num_choices < 1:
raise ValueError("empty range for randrange(%r, %r, %r)" % (start, stop, step))
# Pick a random number in the range of possible numbers
r = num_choices
while r >= num_choices:
r = self.getrandbits(size(num_choices))
return start + (step * r)
def test_size(self):
self.assertEqual(number.size(2),2)
self.assertEqual(number.size(3),2)
self.assertEqual(number.size(0xa2),8)
self.assertEqual(number.size(0xa2ba40),8*3)
self.assertEqual(number.size(0xa2ba40ee07e3b2bd2f02ce227f36a195024486e49c19cb41bbbdfbba98b22b0e577c2eeaffa20d883a76e65e394c69d4b3c05a1e8fadda27edb2a42bc000fe888b9b32c22d15add0cd76b3e7936e19955b220dd17d4ea904b1ec102b2e4de7751222aa99151024c7cb41cc5ea21d00eeb41f7c800834d2c6e06bce3bce7ea9a5L), 1024)
def setUp(self):
global DSA, Random, bytes_to_long, size
from Crypto.PublicKey import DSA
from Crypto import Random
from Crypto.Util.number import bytes_to_long, inverse, size
self.dsa = DSA
def _check_public_key(self, dsaObj):
k = a2b_hex(self.k)
m_hash = a2b_hex(self.m_hash)
# Check capabilities
self.assertEqual(0, dsaObj.has_private())
self.assertEqual(1, dsaObj.can_sign())
self.assertEqual(0, dsaObj.can_encrypt())
self.assertEqual(0, dsaObj.can_blind())
# Check dsaObj.[ygpq] -> dsaObj.key.[ygpq] mapping
self.assertEqual(dsaObj.y, dsaObj.key.y)
self.assertEqual(dsaObj.g, dsaObj.key.g)
self.assertEqual(dsaObj.p, dsaObj.key.p)
self.assertEqual(dsaObj.q, dsaObj.key.q)
# Check that private parameters are all missing
self.assertEqual(0, hasattr(dsaObj, 'x'))
self.assertEqual(0, hasattr(dsaObj.key, 'x'))
# Sanity check key data
self.assertEqual(1, dsaObj.p > dsaObj.q) # p > q
self.assertEqual(160, size(dsaObj.q)) # size(q) == 160 bits
self.assertEqual(0, (dsaObj.p - 1) % dsaObj.q) # q is a divisor of p-1
# Public-only key objects should raise an error when .sign() is called
self.assertRaises(TypeError, dsaObj.sign, m_hash, k)
# Check __eq__ and __ne__
self.assertEqual(dsaObj.publickey() == dsaObj.publickey(),True) # assert_
self.assertEqual(dsaObj.publickey() != dsaObj.publickey(),False) # failIf
def size(self):
"""Return the maximum number of bits that can be encrypted"""
return size(self.p) - 1
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 size(self):
return number.size(self.p) - 1
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 = long(e)
# Generate the prime factors of n
if progress_func:
progress_func('p,q\n')
p = q = 1L
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
def size(self):
"""size() : int
Return the maximum number of bits that can be handled by this key.
"""
return number.size(self.n) - 1
def randrange(self, *args):
"""randrange([start,] stop[, step]):
Return a randomly-selected element from range(start, stop, step)."""
if len(args) == 3:
(start, stop, step) = args
elif len(args) == 2:
(start, stop) = args
step = 1
elif len(args) == 1:
(stop,) = args
start = 0
step = 1
else:
raise TypeError("randrange expected at most 3 arguments, got %d" % (len(args),))
if (not isinstance(start, (int, long))
or not isinstance(stop, (int, long))
or not isinstance(step, (int, long))):
raise TypeError("randrange requires integer arguments")
if step == 0:
raise ValueError("randrange step argument must not be zero")
num_choices = ceil_div(stop - start, step)
if num_choices < 0:
num_choices = 0
if num_choices < 1:
raise ValueError("empty range for randrange(%r, %r, %r)" % (start, stop, step))
# Pick a random number in the range of possible numbers
r = num_choices
while r >= num_choices:
r = self.getrandbits(size(num_choices))
return start + (step * r)
def test_size(self):
self.assertEqual(number.size(2),2)
self.assertEqual(number.size(3),2)
self.assertEqual(number.size(0xa2),8)
self.assertEqual(number.size(0xa2ba40),8*3)
self.assertEqual(number.size(0xa2ba40ee07e3b2bd2f02ce227f36a195024486e49c19cb41bbbdfbba98b22b0e577c2eeaffa20d883a76e65e394c69d4b3c05a1e8fadda27edb2a42bc000fe888b9b32c22d15add0cd76b3e7936e19955b220dd17d4ea904b1ec102b2e4de7751222aa99151024c7cb41cc5ea21d00eeb41f7c800834d2c6e06bce3bce7ea9a5L), 1024)
def setUp(self):
global DSA, Random, bytes_to_long, size
from Crypto.PublicKey import DSA
from Crypto import Random
from Crypto.Util.number import bytes_to_long, inverse, size
self.dsa = DSA
def _check_public_key(self, dsaObj):
k = a2b_hex(self.k)
m_hash = a2b_hex(self.m_hash)
# Check capabilities
self.assertEqual(0, dsaObj.has_private())
self.assertEqual(1, dsaObj.can_sign())
self.assertEqual(0, dsaObj.can_encrypt())
self.assertEqual(0, dsaObj.can_blind())
# Check dsaObj.[ygpq] -> dsaObj.key.[ygpq] mapping
self.assertEqual(dsaObj.y, dsaObj.key.y)
self.assertEqual(dsaObj.g, dsaObj.key.g)
self.assertEqual(dsaObj.p, dsaObj.key.p)
self.assertEqual(dsaObj.q, dsaObj.key.q)
# Check that private parameters are all missing
self.assertEqual(0, hasattr(dsaObj, 'x'))
self.assertEqual(0, hasattr(dsaObj.key, 'x'))
# Sanity check key data
self.assertEqual(1, dsaObj.p > dsaObj.q) # p > q
self.assertEqual(160, size(dsaObj.q)) # size(q) == 160 bits
self.assertEqual(0, (dsaObj.p - 1) % dsaObj.q) # q is a divisor of p-1
# Public-only key objects should raise an error when .sign() is called
self.assertRaises(TypeError, dsaObj.sign, m_hash, k)
# Check __eq__ and __ne__
self.assertEqual(dsaObj.publickey() == dsaObj.publickey(),True) # assert_
self.assertEqual(dsaObj.publickey() != dsaObj.publickey(),False) # failIf
def size(self):
"""Return the maximum number of bits that can be encrypted"""
return size(self.p) - 1
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 size(self):
return number.size(self.p) - 1
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 = long(e)
# Generate the prime factors of n
if progress_func:
progress_func('p,q\n')
p = q = 1L
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
def size(self):
"""size() : int
Return the maximum number of bits that can be handled by this key.
"""
return number.size(self.n) - 1