本文整理汇总了Python中Cryptodome.Math.Numbers.Integer类的典型用法代码示例。如果您正苦于以下问题:Python Integer类的具体用法?Python Integer怎么用?Python Integer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Integer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, x, y):
self._x = Integer(x)
self._y = Integer(y)
# Buffers
self._common = Integer(0)
self._tmp1 = Integer(0)
self._x3 = Integer(0)
self._y3 = Integer(0)
示例2: test_probable_prime
def test_probable_prime(candidate, randfunc=None):
"""Test if a number is prime.
A number is qualified as prime if it passes a certain
number of Miller-Rabin tests (dependent on the size
of the number, but such that probability of a false
positive is less than 10^-30) and a single Lucas test.
For instance, a 1024-bit candidate will need to pass
4 Miller-Rabin tests.
:Parameters:
candidate : integer
The number to test for primality.
randfunc : callable
The routine to draw random bytes from to select Miller-Rabin bases.
:Returns:
``PROBABLE_PRIME`` if the number if prime with very high probability.
``COMPOSITE`` if the number is a composite.
For efficiency reasons, ``COMPOSITE`` is also returned for small primes.
"""
if randfunc is None:
randfunc = Random.new().read
if not isinstance(candidate, Integer):
candidate = Integer(candidate)
# First, check trial division by the smallest primes
if int(candidate) in _sieve_base:
return PROBABLY_PRIME
try:
map(candidate.fail_if_divisible_by, _sieve_base)
except ValueError:
return COMPOSITE
# These are the number of Miller-Rabin iterations s.t. p(k, t) < 1E-30,
# with p(k, t) being the probability that a randomly chosen k-bit number
# is composite but still survives t MR iterations.
mr_ranges = ((220, 30), (280, 20), (390, 15), (512, 10),
(620, 7), (740, 6), (890, 5), (1200, 4),
(1700, 3), (3700, 2))
bit_size = candidate.size_in_bits()
try:
mr_iterations = list(filter(lambda x: bit_size < x[0],
mr_ranges))[0][1]
except IndexError:
mr_iterations = 1
if miller_rabin_test(candidate, mr_iterations,
randfunc=randfunc) == COMPOSITE:
return COMPOSITE
if lucas_test(candidate) == COMPOSITE:
return COMPOSITE
return PROBABLY_PRIME
示例3: test_several_lengths
def test_several_lengths(self):
prng = SHAKE128.new().update(b('Test'))
for length in range(1, 100):
base = Integer.from_bytes(prng.read(length))
modulus2 = Integer.from_bytes(prng.read(length)) | 1
exponent2 = Integer.from_bytes(prng.read(length))
expected = pow(base, exponent2, modulus2)
result = monty_pow(base, exponent2, modulus2)
self.assertEqual(result, expected)
示例4: test_random_exact_bits
def test_random_exact_bits(self):
for _ in xrange(1000):
a = IntegerGeneric.random(exact_bits=8)
self.failIf(a < 128)
self.failIf(a >= 256)
for bits_value in xrange(1024, 1024 + 8):
a = IntegerGeneric.random(exact_bits=bits_value)
self.failIf(a < 2**(bits_value - 1))
self.failIf(a >= 2**bits_value)
示例5: test_random_max_bits
def test_random_max_bits(self):
flag = False
for _ in xrange(1000):
a = IntegerGeneric.random(max_bits=8)
flag = flag or a < 128
self.failIf(a>=256)
self.failUnless(flag)
for bits_value in xrange(1024, 1024 + 8):
a = IntegerGeneric.random(max_bits=bits_value)
self.failIf(a >= 2**bits_value)
示例6: _sign
def _sign(self, M, K):
if (not hasattr(self, 'x')):
raise TypeError('Private key not available in this object')
p1=self.p-1
K = Integer(K)
if (K.gcd(p1)!=1):
raise ValueError('Bad K value: GCD(K,p-1)!=1')
a=pow(self.g, K, self.p)
t=(Integer(M)-self.x*a) % p1
while t<0: t=t+p1
b=(t*K.inverse(p1)) % p1
return [int(a), int(b)]
示例7: verify
def verify(self, msg_hash, signature):
"""Verify that a certain DSS signature is authentic.
This function checks if the party holding the private half of the key
really signed the message.
:Parameters:
msg_hash : hash object
The hash that was carried out over the message.
This is an object belonging to the `Cryptodome.Hash` module.
Under mode *'fips-186-3'*, the hash must be a FIPS
approved secure hash (SHA-1 or a member of the SHA-2 family),
of cryptographic strength appropriate for the DSA key.
For instance, a 3072/256 DSA key can only be used in
combination with SHA-512.
signature : byte string
The signature that needs to be validated.
:Raise ValueError:
If the signature is not authentic.
"""
if not self._valid_hash(msg_hash):
raise ValueError("Hash does not belong to SHS")
if self._encoding == 'binary':
if len(signature) != (2 * self._order_bytes):
raise ValueError("The signature is not authentic (length)")
r_prime, s_prime = [Integer.from_bytes(x)
for x in (signature[:self._order_bytes],
signature[self._order_bytes:])]
else:
try:
der_seq = DerSequence().decode(signature)
except (ValueError, IndexError):
raise ValueError("The signature is not authentic (DER)")
if len(der_seq) != 2 or not der_seq.hasOnlyInts():
raise ValueError("The signature is not authentic (DER content)")
r_prime, s_prime = der_seq[0], der_seq[1]
if not (0 < r_prime < self._order) or not (0 < s_prime < self._order):
raise ValueError("The signature is not authentic (d)")
z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes])
result = self._key._verify(z, (r_prime, s_prime))
if not result:
raise ValueError("The signature is not authentic")
# Make PyCryptodome code to fail
return False
示例8: _decrypt
def _decrypt(self, ciphertext):
if not 0 < ciphertext < self._n:
raise ValueError("Ciphertext too large")
if not self.has_private():
raise TypeError("This is not a private key")
# Blinded RSA decryption (to prevent timing attacks):
# Step 1: Generate random secret blinding factor r,
# such that 0 < r < n-1
r = Integer.random_range(min_inclusive=1, max_exclusive=self._n)
# Step 2: Compute c' = c * r**e mod n
cp = Integer(ciphertext) * pow(r, self._e, self._n) % self._n
# Step 3: Compute m' = c'**d mod n (ordinary RSA decryption)
m1 = pow(cp, self._d % (self._p - 1), self._p)
m2 = pow(cp, self._d % (self._q - 1), self._q)
h = m2 - m1
while h < 0:
h += self._q
h = (h * self._u) % self._q
mp = h * self._p + m1
# Step 4: Compute m = m**(r-1) mod n
result = (r.inverse(self._n) * mp) % self._n
# Verify no faults occured
if ciphertext != pow(result, self._e, self._n):
raise ValueError("Fault detected in RSA decryption")
return result
示例9: _import_public_der
def _import_public_der(curve_name, publickey):
# We only support P-256 named curves for now
if curve_name != _curve.oid:
raise ValueError("Unsupport curve")
# ECPoint ::= OCTET STRING
# We support only uncompressed points
order_bytes = _curve.order.size_in_bytes()
if len(publickey) != (1 + 2 * order_bytes) or bord(publickey[0]) != 4:
raise ValueError("Only uncompressed points are supported")
point_x = Integer.from_bytes(publickey[1:order_bytes+1])
point_y = Integer.from_bytes(publickey[order_bytes+1:])
return construct(curve="P-256", point_x=point_x, point_y=point_y)
示例10: __mul__
def __mul__(self, scalar):
"""Return a new point, the scalar product of this one"""
if scalar < 0:
raise ValueError("Scalar multiplication only defined for non-negative integers")
# Trivial results
if scalar == 0 or self.is_point_at_infinity():
return self.point_at_infinity()
elif scalar == 1:
return self.copy()
# Scalar randomization
scalar_blind = Integer.random(exact_bits=64) * _curve.order + scalar
# Montgomery key ladder
r = [self.point_at_infinity().copy(), self.copy()]
bit_size = int(scalar_blind.size_in_bits())
scalar_int = int(scalar_blind)
for i in range(bit_size, -1, -1):
di = scalar_int >> i & 1
r[di ^ 1] += r[di]
r[di].double()
return r[0]
示例11: _bits2int
def _bits2int(self, bstr):
"""See 2.3.2 in RFC6979"""
result = Integer.from_bytes(bstr)
q_len = self._order.size_in_bits()
b_len = len(bstr) * 8
if b_len > q_len:
result >>= (b_len - q_len)
return result
示例12: generate_probable_prime
def generate_probable_prime(**kwargs):
"""Generate a random probable prime.
The prime will not have any specific properties
(e.g. it will not be a *strong* prime).
Random numbers are evaluated for primality until one
passes all tests, consisting of a certain number of
Miller-Rabin tests with random bases followed by
a single Lucas test.
The number of Miller-Rabin iterations is chosen such that
the probability that the output number is a non-prime is
less than 1E-30 (roughly 2^{-100}).
This approach is compliant to `FIPS PUB 186-4`__.
:Keywords:
exact_bits : integer
The desired size in bits of the probable prime.
It must be at least 160.
randfunc : callable
An RNG function where candidate primes are taken from.
prime_filter : callable
A function that takes an Integer as parameter and returns
True if the number can be passed to further primality tests,
False if it should be immediately discarded.
:Return:
A probable prime in the range 2^exact_bits > p > 2^(exact_bits-1).
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
"""
exact_bits = kwargs.pop("exact_bits", None)
randfunc = kwargs.pop("randfunc", None)
prime_filter = kwargs.pop("prime_filter", lambda x: True)
if kwargs:
print "Unknown parameters:", kwargs.keys()
if exact_bits is None:
raise ValueError("Missing exact_bits parameter")
if exact_bits < 160:
raise ValueError("Prime number is not big enough.")
if randfunc is None:
randfunc = Random.new().read
result = COMPOSITE
while result == COMPOSITE:
candidate = Integer.random(exact_bits=exact_bits,
randfunc=randfunc) | 1
if not prime_filter(candidate):
continue
result = test_probable_prime(candidate, randfunc)
return candidate
示例13: _import_public_der
def _import_public_der(curve_oid, ec_point):
"""Convert an encoded EC point into an EccKey object
curve_name: string with the OID of the curve
ec_point: byte string with the EC point (not DER encoded)
"""
# We only support P-256 named curves for now
if curve_oid != _curve.oid:
raise UnsupportedEccFeature("Unsupported ECC curve (OID: %s)" % curve_oid)
# See 2.2 in RFC5480 and 2.3.3 in SEC1
# The first byte is:
# - 0x02: compressed, only X-coordinate, Y-coordinate is even
# - 0x03: compressed, only X-coordinate, Y-coordinate is odd
# - 0x04: uncompressed, X-coordinate is followed by Y-coordinate
#
# PAI is in theory encoded as 0x00.
order_bytes = _curve.order.size_in_bytes()
point_type = bord(ec_point[0])
# Uncompressed point
if point_type == 0x04:
if len(ec_point) != (1 + 2 * order_bytes):
raise ValueError("Incorrect EC point length")
x = Integer.from_bytes(ec_point[1:order_bytes+1])
y = Integer.from_bytes(ec_point[order_bytes+1:])
# Compressed point
elif point_type in (0x02, 0x3):
if len(ec_point) != (1 + order_bytes):
raise ValueError("Incorrect EC point length")
x = Integer.from_bytes(ec_point[1:])
y = (x**3 - x*3 + _curve.b).sqrt(_curve.p) # Short Weierstrass
if point_type == 0x02 and y.is_odd():
y = _curve.p - y
if point_type == 0x03 and y.is_even():
y = _curve.p - y
else:
raise ValueError("Incorrect EC point encoding")
return construct(curve="P-256", point_x=x, point_y=y)
示例14: _decrypt
def _decrypt(self, M):
if (not hasattr(self, 'x')):
raise TypeError('Private key not available in this object')
r = Integer.random_range(min_inclusive=2,
max_exclusive=self.p-1,
randfunc=self._randfunc)
a_blind = (pow(self.g, r, self.p) * M[0]) % self.p
ax=pow(a_blind, self.x, self.p)
plaintext_blind = (ax.inverse(self.p) * M[1] ) % self.p
plaintext = (plaintext_blind * pow(self.y, r, self.p)) % self.p
return int(plaintext)
示例15: _get_weak_domain
def _get_weak_domain(self):
from Cryptodome.Math.Numbers import Integer
from Cryptodome.Math import Primality
p = Integer(4)
while p.size_in_bits() != 1024 or Primality.test_probable_prime(p) != Primality.PROBABLY_PRIME:
q1 = Integer.random(exact_bits=80)
q2 = Integer.random(exact_bits=80)
q = q1 * q2
z = Integer.random(exact_bits=1024-160)
p = z * q + 1
h = Integer(2)
g = 1
while g == 1:
g = pow(h, z, p)
h += 1
return (p, q, g)