def generate(bits, randfunc=None, e=65537): """allow to generate small keys for test purposes """ if e % 2 == 0 or e < 3: raise ValueError( "RSA public exponent must be a positive, odd integer larger than 2." ) if randfunc is None: randfunc = Random.get_random_bytes d = n = Integer(1) e = Integer(e) while n.size_in_bits() != bits and d < (1 << (bits // 2)): # Generate the prime factors of n: p and q. # By construciton, their product is always # 2^{bits-1} < p*q < 2^bits. size_q = bits // 2 size_p = bits - size_q min_p = min_q = (Integer(1) << (2 * size_q - 1)).sqrt() if size_q != size_p: min_p = (Integer(1) << (2 * size_p - 1)).sqrt() def filter_p(candidate): return candidate > min_p and (candidate - 1).gcd(e) == 1 p = generate_probable_prime(exact_bits=size_p, randfunc=randfunc, prime_filter=filter_p) min_distance = Integer(1) << (max(bits // 2 - 100, 10)) def filter_q(candidate): return (candidate > min_q and (candidate - 1).gcd(e) == 1 and abs(candidate - p) > min_distance) q = generate_probable_prime(exact_bits=size_q, randfunc=randfunc, prime_filter=filter_q) n = p * q lcm = (p - 1).lcm(q - 1) d = e.inverse(lcm) if p > q: p, q = q, p u = p.inverse(q) return RSA.RsaKey(n=n, e=e, d=d, p=p, q=q, u=u)
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 map(int, (a, b))
def xy(self): modulus_bytes = self.size_in_bytes() xb = bytearray(modulus_bytes) yb = bytearray(modulus_bytes) result = _ec_lib.ec_ws_get_xy(c_uint8_ptr(xb), c_uint8_ptr(yb), c_size_t(modulus_bytes), self._point.get()) if result: raise ValueError("Error %d while encoding an EC point" % result) return (Integer(bytes_to_long(xb)), Integer(bytes_to_long(yb)))
def _generate_domain(L, randfunc): """Generate a new set of DSA domain parameters""" N = {1024: 160, 2048: 224, 3072: 256}.get(L) if N is None: raise ValueError("Invalid modulus length (%d)" % L) outlen = SHA256.digest_size * 8 n = (L + outlen - 1) // outlen - 1 # ceil(L/outlen) -1 b_ = L - 1 - (n * outlen) # Generate q (A.1.1.2) q = Integer(4) upper_bit = 1 << (N - 1) while test_probable_prime(q, randfunc) != PROBABLY_PRIME: seed = randfunc(64) U = Integer.from_bytes(SHA256.new(seed).digest()) & (upper_bit - 1) q = U | upper_bit | 1 assert (q.size_in_bits() == N) # Generate p (A.1.1.2) offset = 1 upper_bit = 1 << (L - 1) while True: V = [ SHA256.new(seed + Integer(offset + j).to_bytes()).digest() for j in range(n + 1) ] V = [Integer.from_bytes(v) for v in V] W = sum([V[i] * (1 << (i * outlen)) for i in range(n)], (V[n] & (1 << b_ - 1)) * (1 << (n * outlen))) X = Integer(W + upper_bit) # 2^{L-1} < X < 2^{L} assert (X.size_in_bits() == L) c = X % (q * 2) p = X - (c - 1) # 2q divides (p-1) if p.size_in_bits() == L and \ test_probable_prime(p, randfunc) == PROBABLY_PRIME: break offset += n + 1 # Generate g (A.2.3, index=1) e = (p - 1) // q for count in itertools.count(1): U = seed + b("ggen") + bchr(1) + Integer(count).to_bytes() W = Integer.from_bytes(SHA256.new(U).digest()) g = pow(W, e, p) if g != 1: break return (p, q, g, seed)
def construct(**kwargs): """Build a new ECC key (private or public) starting from some base components. Args: curve (string): Mandatory. It must be "P-256", "prime256v1" or "secp256r1". d (integer): Only for a private key. It must be in the range ``[1..order-1]``. point_x (integer): Mandatory for a public key. X coordinate (affine) of the ECC point. point_y (integer): Mandatory for a public key. Y coordinate (affine) of the ECC point. Returns: :class:`EccKey` : a new ECC key object """ point_x = kwargs.pop("point_x", None) point_y = kwargs.pop("point_y", None) if "point" in kwargs: raise TypeError("Unknown keyword: point") if None not in (point_x, point_y): kwargs["point"] = EccPoint(point_x, point_y) # Validate that the point is on the P-256 curve eq1 = pow(Integer(point_y), 2, _curve.p) x = Integer(point_x) eq2 = pow(x, 3, _curve.p) x *= -3 eq2 += x eq2 += _curve.b eq2 %= _curve.p if eq1 != eq2: raise ValueError("The point is not on the curve") # Validate that the private key matches the public one d = kwargs.get("d", None) if d is not None and "point" in kwargs: pub_key = _curve.G * d if pub_key.x != point_x or pub_key.y != point_y: raise ValueError("Private and public ECC keys do not match") return EccKey(**kwargs)
def verify(self, msg_hash, signature): """Check if a certain (EC)DSA signature is authentic. :parameter msg_hash: The hash that was carried out over the message. This is an object belonging to the :mod:`Crypto.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. :type msg_hash: hash object :parameter signature: The signature that needs to be validated :type signature: byte string :raise ValueError: if the signature is not authentic """ if not self._valid_hash(msg_hash): raise ValueError("Hash is not sufficiently strong") 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, strict=True) 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 = Integer(der_seq[0]), Integer(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 PyCrypto code to fail return False
def test_scalar_multiply(self): d = 0xa78ccc30eaca0fcc8e36b2dd6fbb03df06d37f52711e6363aaf1d73b pointRx = 0x96a7625e92a8d72bff1113abdb95777e736a14c6fdaacc392702bca4 pointRy = 0x0f8e5702942a3c5e13cd2fd5801915258b43dfadc70d15dbada3ed10 pointR = self.pointS * d self.assertEqual(pointR.x, pointRx) self.assertEqual(pointR.y, pointRy) # 0*S pai = self.pointS.point_at_infinity() pointR = self.pointS * 0 self.assertEqual(pointR, pai) # -1*S self.assertRaises(ValueError, lambda: self.pointS * -1) # Reverse order pointR = d * self.pointS self.assertEqual(pointR.x, pointRx) self.assertEqual(pointR.y, pointRy) pointR = Integer(d) * self.pointS self.assertEqual(pointR.x, pointRx) self.assertEqual(pointR.y, pointRy)
def find_generator(p): # Just finds a group generator; not part of the challenge # From https://github.com/Legrandin/pycryptodome/blob/6fb4ca4c73d7e80f336c183dd8ed906d3c4320a2/lib/Crypto/PublicKey/ElGamal.py#L60 p = Integer(p) while 1: # Choose a square residue; it will generate a cyclic group of order q. g = pow(Integer.random_range(min_inclusive=2, max_exclusive=p), 2, p) # We must avoid g=2 because of Bleichenbacher's attack described # in "Generating ElGamal signatures without knowning the secret key", # 1996 if g in (1, 2): continue # Discard g if it divides p-1 because of the attack described # in Note 11.67 (iii) in HAC if (p - 1) % g == 0: continue # g^{-1} must not divide p-1 because of Khadir's attack # described in "Conditions of the generator for forging ElGamal # signature", 2011 ginv = g.inverse(p) if (p - 1) % ginv == 0: continue # Found break return int(g)
def test_scalar_multiply(self): d = 0xa78a236d60baec0c5dd41b33a542463a8255391af64c74ee pointRx = 0x1faee4205a4f669d2d0a8f25e3bcec9a62a6952965bf6d31 pointRy = 0x5ff2cdfa508a2581892367087c696f179e7a4d7e8260fb06 pointR = self.pointS * d self.assertEqual(pointR.x, pointRx) self.assertEqual(pointR.y, pointRy) # 0*S pai = self.pointS.point_at_infinity() pointR = self.pointS * 0 self.assertEqual(pointR, pai) # -1*S self.assertRaises(ValueError, lambda: self.pointS * -1) # Reverse order pointR = d * self.pointS self.assertEqual(pointR.x, pointRx) self.assertEqual(pointR.y, pointRy) pointR = Integer(d) * self.pointS self.assertEqual(pointR.x, pointRx) self.assertEqual(pointR.y, pointRy)
def test_scalar_multiply(self): d = 0xc51e4753afdec1e6b6c6a5b992f43f8dd0c7a8933072708b6522468b2ffb06fd pointRx = 0x51d08d5f2d4278882946d88d83c97d11e62becc3cfc18bedacc89ba34eeca03f pointRy = 0x75ee68eb8bf626aa5b673ab51f6e744e06f8fcf8a6c0cf3035beca956a7b41d5 pointR = self.pointS * d self.assertEqual(pointR.x, pointRx) self.assertEqual(pointR.y, pointRy) # 0*S pai = self.pointS.point_at_infinity() pointR = self.pointS * 0 self.assertEqual(pointR, pai) # -1*S self.assertRaises(ValueError, lambda: self.pointS * -1) # Reverse order pointR = d * self.pointS self.assertEqual(pointR.x, pointRx) self.assertEqual(pointR.y, pointRy) pointR = Integer(d) * self.pointS self.assertEqual(pointR.x, pointRx) self.assertEqual(pointR.y, pointRy)
def _importKeyDER(extern_key, passphrase, verify_x509_cert): """Import an RSA key (public or private half), encoded in DER form.""" try: der = DerSequence().decode(extern_key) # Try PKCS#1 first, for a private key if len(der) == 9 and der.hasOnlyInts() and der[0] == 0: # ASN.1 RSAPrivateKey element del der[6:] # Remove d mod (p-1), # d mod (q-1), and # q^{-1} mod p der.append(Integer(der[4]).inverse(der[5])) # Add p^{-1} mod q del der[0] # Remove version return construct(der[:]) # Keep on trying PKCS#1, but now for a public key if len(der) == 2: try: # The DER object is an RSAPublicKey SEQUENCE with # two elements if der.hasOnlyInts(): return construct(der[:]) # The DER object is a SubjectPublicKeyInfo SEQUENCE # with two elements: an 'algorithmIdentifier' and a # 'subjectPublicKey'BIT STRING. # 'algorithmIdentifier' takes the value given at the # module level. # 'subjectPublicKey' encapsulates the actual ASN.1 # RSAPublicKey element. if der[0] == algorithmIdentifier: bitmap = DerBitString().decode(der[1]) rsaPub = DerSequence().decode(bitmap.value) if len(rsaPub) == 2 and rsaPub.hasOnlyInts(): return construct(rsaPub[:]) except (ValueError, EOFError): pass # Try to see if this is an X.509 DER certificate # (Certificate ASN.1 type) if len(der) == 3: from Crypto.PublicKey import _extract_sp_info try: sp_info = _extract_sp_info(der) if verify_x509_cert: raise NotImplementedError("X.509 certificate validation is not supported") return _importKeyDER(sp_info, passphrase, False) except ValueError: pass # Try PKCS#8 (possibly encrypted) k = PKCS8.unwrap(extern_key, passphrase) if k[0] == oid: return _importKeyDER(k[1], passphrase, False) except (ValueError, EOFError): pass raise ValueError("RSA key format is not supported")
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
def derive_pwe_ecc(password, addr1, addr2, curve_name="p256"): curve = ECC._curves[curve_name] bits = curve.modulus_bits assert bits % 8 == 0 addr1 = binascii.unhexlify(addr1.replace(':', '')) addr2 = binascii.unhexlify(addr2.replace(':', '')) hash_pw = addr1 + addr2 if addr1 > addr2 else addr2 + addr1 for counter in range(1, 100): hash_data = str2bytes(password) + struct.pack("<B", counter) pwd_seed = HMAC256(hash_pw, hash_data) log(DEBUG, "PWD-seed: %s" % pwd_seed) pwd_value = KDF_Length(pwd_seed, "SAE Hunting and Pecking", curve.p.to_bytes(bits // 8), bits) log(DEBUG, "PWD-value: %s" % pwd_value) pwd_value = int(binascii.hexlify(pwd_value), 16) if pwd_value >= curve.p: continue x = Integer(pwd_value) y_sqr = (x**3 - x * 3 + curve.b) % curve.p if legendre_symbol(y_sqr, curve.p) != 1: continue y = y_sqr.sqrt(curve.p) y_bit = getord(pwd_seed[-1]) & 1 if y & 1 == y_bit: return ECC.EccPoint(x, y, curve_name) else: return ECC.EccPoint(x, curve.p - y, curve_name)
def __init__(self, **kwargs): """Create a new ECC key Keywords: curve : string It must be *"p256"*, *"P-256"*, *"prime256v1"* or *"secp256r1"*. d : integer Only for a private key. It must be in the range ``[1..order-1]``. point : EccPoint Mandatory for a public key. If provided for a private key, the implementation will NOT check whether it matches ``d``. """ kwargs_ = dict(kwargs) curve_name = kwargs_.pop("curve", None) self._d = kwargs_.pop("d", None) self._point = kwargs_.pop("point", None) if kwargs_: raise TypeError("Unknown parameters: " + str(kwargs_)) if curve_name not in _curves: raise ValueError("Unsupported curve (%s)", curve_name) self._curve = _curves[curve_name] if self._d is None: if self._point is None: raise ValueError( "Either private or public ECC component must be specified, not both" ) else: self._d = Integer(self._d) if not 1 <= self._d < self._curve.order: raise ValueError("Invalid ECC private component") self.curve = self._curve.desc
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") e, d, n, p, q, u = [ self._key[comp] for comp in 'e', 'd', 'n', 'p', 'q', 'u' ] # 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=n) # Step 2: Compute c' = c * r**e mod n cp = Integer(ciphertext) * pow(r, e, n) % n # Step 3: Compute m' = c'**d mod n (ordinary RSA decryption) m1 = pow(cp, d % (p - 1), p) m2 = pow(cp, d % (q - 1), q) h = m2 - m1 while h < 0: h += q h = (h * u) % q mp = h * p + m1 # Step 4: Compute m = m**(r-1) mod n result = (r.inverse(n) * mp) % n # Verify no faults occured if ciphertext != pow(result, e, n): raise ValueError("Fault detected in RSA decryption") return result
def verify(self, msg_hash, signature): """Check if a certain (EC)DSA signature is authentic. Args: msg_hash (hash object): The hash that was carried out over the message. This is an object belonging to the :mod:`Crypto.Hash` module. Under mode ``'fips-186-3'``, the hash must be a FIPS approved secure hash (SHA-2 or SHA-3). signature (``bytes``): 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 is not sufficiently strong") 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, strict=True) 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 = Integer(der_seq[0]), Integer(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 PyCrypto code to fail return False
def __init__(self, key, encoding, order, randfunc): super(FipsDsaSigScheme, self).__init__(key, encoding, order) self._randfunc = randfunc L = Integer(key.p).size_in_bits() if (L, self._order_bits) not in self._fips_186_3_L_N: error = ("L/N (%d, %d) is not compliant to FIPS 186-3" % (L, self._order_bits)) raise ValueError(error)
def rsa_mega_decrypt(self, ciphertext): from Crypto.Math.Numbers import Integer if not 0 < ciphertext < self._n: raise ValueError("Ciphertext too large") if not self.has_private(): raise TypeError("This is not a private key") return pow(Integer(ciphertext), self._d, self._n)
def A(params): p, q, s, r = params['p'], params['q'], params['s'], params['r'] y, h, g, m = params['y'], params['h'], params['g'], params['m'] h = int(h, 16) for k in range(1, 2**16): if pow(g, k, p) % q == r: recovered_k = k break k = Integer(recovered_k) # s <- k^-1(h + xr) mod q # Then x = r^-1(ks - h) x = Integer(Integer(s) * k % q - h) * Integer(r).inverse(q) % q assert s == k.inverse(q) * (Integer(h) + x * r) % q return (x + ((p - 1) // 2) * 0) % p, k
def xy(self): xb = bytearray(32) yb = bytearray(32) result = _ec_lib.ec_ws_get_xy(c_uint8_ptr(xb), c_uint8_ptr(yb), c_size_t(len(xb)), self._point.get()) if result: raise ValueError("Error %d while encoding an EC point" % result) return [Integer(bytes_to_long(c)) for c in (xb, yb)]
def _verify(self, m, sig): r, s = sig y, q, p, g = [self._key[comp] for comp in ['y', 'q', 'p', 'g']] if not (0 < r < q) or not (0 < s < q): return False w = Integer(s).inverse(q) u1 = (w * m) % q u2 = (w * r) % q v = (pow(g, u1, p) * pow(y, u2, p) % p) % q return v == r
def _verify(self, M, sig): sig = [Integer(x) for x in sig] if sig[0] < 1 or sig[0] > self.p - 1: return 0 v1 = pow(self.y, sig[0], self.p) v1 = (v1 * pow(sig[0], sig[1], self.p)) % self.p v2 = pow(self.g, M, self.p) if v1 == v2: return 1 return 0
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: list(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([x for x in mr_ranges if bit_size < x[0]])[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
def _get_weak_domain(self): from Crypto.Math.Numbers import Integer from Crypto.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)
def gen_dsa_from_q(bits, q): q = Integer(q) # Generate p (A.1.1.2) L = bits outlen = SHA256.digest_size * 8 n = (L + outlen - 1) // outlen - 1 b = L - 1 - (n * outlen) seed = b'Crypto' offset = 1 upper_bit = 1 << (L - 1) while True: V = [ SHA256.new(seed + Integer(offset + j).to_bytes()).digest() for j in range(n + 1) ] V = [Integer.from_bytes(v) for v in V] W = sum([V[i] * (1 << (i * outlen)) for i in range(n)], (V[n] & ((1 << b) - 1)) * (1 << (n * outlen))) X = Integer(W + upper_bit) # 2^{L-1} < X < 2^{L} assert (X.size_in_bits() == L) c = X % (q * 2) p = X - (c - 1) # 2q divides (p-1) if p.size_in_bits() == L and isPrime(int(p)): break offset += n + 1 # Generate g (A.2.3, index=1) e = (p - 1) // q for count in itertools.count(1): U = seed + b"ggen" + bytes([1]) + Integer(count).to_bytes() W = Integer.from_bytes(SHA256.new(U).digest()) g = pow(W, e, p) if g != 1: break return int(p), int(g)
def rsa_hex(data,key,a): try: from Crypto.Math.Numbers import Integer # key1=base64.b64decode(key) modulus = int('a5aeb8c636ef1fda5a7a17a2819e51e1ea6e0cceb24b95574ae026536243524f322807df2531a42139389674545f4c596db162f6e6bbb26498baab074c036777', 16) exponent = int('10001', 16) # rsa_pubkey = rsa.PublicKey(modulus, exponent) # rsaKey = RSA.importKey(key1) rsaKey = RSA.construct([Integer(modulus),Integer(exponent)]) # rsaKey.e = exponent # rsaKey.n = modulus cipher = no5_Cipher(rsaKey,a) cipher_text = bytes(data, encoding='utf-8') cipher_text_rsa = cipher.encrypt(cipher_text) k=cipher_text_rsa.hex() if k == "088c7040cb4833238dc99e0c4650e446135484380951f4b4f31a5f9d93f1d330d9f6e3efdb02cbfdc10c0ae19c6706aed1b883522f183fc58830e8b77879417f": print ('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') return cipher_text_rsa.hex() except Exception as e: print(e)
def paramGen_old(): with open('/dev/urandom', 'rb') as f: salt = f.read(12) with open('./salt.bin', 'wb') as f: f.write(salt) # Invalid DSA with gen_smooth_prime(128, 8) q = Integer(gen_smooth(128, 8)) p, g = map(Integer, gen_dsa_from_q(768, q)) c = Integer.random(exact_bits=q.size_in_bits() + 64) x = c % (q - 1) + 1 y = pow(g, x, p) key_dict = {'y': y, 'g': g, 'p': p, 'q': q, 'x': x} dsa = myDSA(key_dict, salt) with open('./vuln_pub.pem', 'w') as f: f.write(dsa.export_key('pub')) with open('./vuln_priv.pem', 'w') as f: f.write(dsa.export_key('priv')) # Valid DSA q = Integer(getPrime(128)) p, g = map(Integer, gen_dsa_from_q(768, q)) c = Integer.random(exact_bits=q.size_in_bits() + 64) x = c % (q - 1) + 1 y = pow(g, x, p) key_dict = {'y': y, 'g': g, 'p': p, 'q': q, 'x': x} dsa = myDSA(key_dict, salt) with open('./pub.pem', 'w') as f: f.write(dsa.export_key('pub')) with open('./priv.pem', 'w') as f: f.write(dsa.export_key('priv'))
def __repr__(self): attrs = [] for k in self._keydata: if k == 'p': bits = Integer(self.p).size_in_bits() attrs.append("p(%d)" % (bits, )) elif hasattr(self, 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))
def construct(tup): r"""Construct an ElGamal key from a tuple of valid ElGamal components. The modulus *p* must be a prime. The following conditions must apply: .. math:: \begin{align} &1 < g < p-1 \\ &g^{p-1} = 1 \text{ mod } 1 \\ &1 < x < p-1 \\ &g^x = y \text{ mod } p \end{align} Args: tup (tuple): A tuple with either 3 or 4 integers, in the following order: 1. Modulus (*p*). 2. Generator (*g*). 3. Public key (*y*). 4. Private key (*x*). Optional. Raises: ValueError: when the key being imported fails the most basic ElGamal validity checks. Returns: an :class:`ElGamalKey` object """ obj = ElGamalKey() if len(tup) not in [3, 4]: raise ValueError('argument for construct() wrong length') for i in range(len(tup)): field = obj._keydata[i] setattr(obj, field, Integer(tup[i])) fmt_error = test_probable_prime(obj.p) == COMPOSITE fmt_error |= obj.g <= 1 or obj.g >= obj.p fmt_error |= pow(obj.g, obj.p - 1, obj.p) != 1 fmt_error |= obj.y < 1 or obj.y >= obj.p if len(tup) == 4: fmt_error |= obj.x <= 1 or obj.x >= obj.p fmt_error |= pow(obj.g, obj.x, obj.p) != obj.y if fmt_error: raise ValueError("Invalid ElGamal key components") return obj
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)