Python Crypto.Util.number.inverse() Examples
The following are 30
code examples of Crypto.Util.number.inverse().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
Crypto.Util.number
, or try the search function
.
Example #1
Source File: algorithms.py From wincrypto with MIT License | 6 votes |
def export_privatekeyblob(self): key = self.key.key n = key.n e = key.e d = key.d p = key.p q = key.q n_bytes = long_to_bytes(n)[::-1] key_len = len(n_bytes) * 8 result = PUBLICKEYSTRUC_s.pack(bType_PRIVATEKEYBLOB, CUR_BLOB_VERSION, CALG_RSA_KEYX) result += RSAPUBKEY_s.pack(PRIVATEKEYBLOB_MAGIC, key_len, e) result += n_bytes result += long_to_bytes(p, key_len / 16)[::-1] result += long_to_bytes(q, key_len / 16)[::-1] result += long_to_bytes(d % (p - 1), key_len / 16)[::-1] result += long_to_bytes(d % (q - 1), key_len / 16)[::-1] result += long_to_bytes(inverse(q, p), key_len / 16)[::-1] result += long_to_bytes(d, key_len / 8)[::-1] return result
Example #2
Source File: ElGamal.py From earthengine with MIT License | 5 votes |
def _sign(self, M, K): if (not hasattr(self, 'x')): raise TypeError('Private key not available in this object') p1=self.p-1 if (GCD(K, p1)!=1): raise ValueError('Bad K value: GCD(K,p-1)!=1') a=pow(self.g, K, self.p) t=(M-self.x*a) % p1 while t<0: t=t+p1 b=(t*inverse(K, p1)) % p1 return (a, b)
Example #3
Source File: test_RSA.py From android_universal with MIT License | 5 votes |
def _exercise_primitive(self, rsaObj): # Since we're using a randomly-generated key, we can't check the test # vector, but we can make sure encryption and decryption are inverse # operations. ciphertext = bytes_to_long(a2b_hex(self.ciphertext)) # Test decryption plaintext = rsaObj._decrypt(ciphertext) # Test encryption (2 arguments) new_ciphertext2 = rsaObj._encrypt(plaintext) self.assertEqual(ciphertext, new_ciphertext2)
Example #4
Source File: test_RSA.py From android_universal with MIT License | 5 votes |
def test_construct_bad_key6(self): tup = (self.n, self.e, self.d, self.p, self.q, 10) self.assertRaises(ValueError, self.rsa.construct, tup) from Crypto.Util.number import inverse tup = (self.n, self.e, self.d, self.p, self.q, inverse(self.q, self.p)) self.assertRaises(ValueError, self.rsa.construct, tup)
Example #5
Source File: test_RSA.py From android_universal with MIT License | 5 votes |
def setUp(self): global RSA, Random, bytes_to_long from Crypto.PublicKey import RSA from Crypto import Random from Crypto.Util.number import bytes_to_long, inverse self.n = bytes_to_long(a2b_hex(self.modulus)) self.p = bytes_to_long(a2b_hex(self.prime_factor)) # Compute q, d, and u from n, e, and p self.q = self.n // self.p self.d = inverse(self.e, (self.p-1)*(self.q-1)) self.u = inverse(self.p, self.q) # u = e**-1 (mod q) self.rsa = RSA
Example #6
Source File: formutil.py From asterix with GNU Lesser General Public License v2.1 | 5 votes |
def dict2RSA(**kw): """ Create Crypto.PublicKey.RSA from dict Required RSA priv. key params (as long) n, e - modulus and public exponent (public key only) n, d, e - modulus, private and public exponent or p, q, e - primes p, q, and public exponent e If also dp, dq, qinv present, they are checked to be consistent. Default value for e is 0x10001 Return Crypto.PublicKey.RSA object dp = d mod (p-1), dq = d mod (q-1), q*qinv mod p = 1 """ for par in ('n', 'd', 'p', 'q', 'dp', 'dq', 'qinv'): if par in kw: assert isinstance(long(kw[par]), long), \ "RSA parameter %s must be long" % par e = long(kw.get('e', 0x10001L)) if all([par not in kw for par in ('d', 'p', 'q', 'dp', 'dq', 'qinv')]): assert 'n' in kw, "At least modulus must be in dict" return RSA.construct((kw['n'], e)) if 'n' in kw and 'd' in kw: return RSA.construct((kw['n'], e, kw['d'])) assert 'p' in kw and 'q' in kw, "Either n, d or p, q must be in dict" p = kw['p'] q = kw['q'] n = p*q d = number.inverse(e, (p-1)*(q-1)) if 'd' in kw: assert d == kw['d'], "Inconsinstent private exponent" if 'dp' in kw: assert d % (p-1) == kw['dp'], "Inconsistent d mod (p-1)" if 'dq' in kw: assert d % (q-1) == kw['dq'], "Inconsistent d mod (q-1)" u = number.inverse(q, p) if 'qinv' in kw: assert u == kw['qinv'], "Inconsistent q inv" return RSA.construct((n, e, d, q, p, u))
Example #7
Source File: test_RSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def _exercise_primitive(self, rsaObj): # Since we're using a randomly-generated key, we can't check the test # vector, but we can make sure encryption and decryption are inverse # operations. ciphertext = bytes_to_long(a2b_hex(self.ciphertext)) # Test decryption plaintext = rsaObj._decrypt(ciphertext) # Test encryption (2 arguments) new_ciphertext2 = rsaObj._encrypt(plaintext) self.assertEqual(ciphertext, new_ciphertext2)
Example #8
Source File: test_RSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_construct_bad_key6(self): tup = (self.n, self.e, self.d, self.p, self.q, 10) self.assertRaises(ValueError, self.rsa.construct, tup) from Crypto.Util.number import inverse tup = (self.n, self.e, self.d, self.p, self.q, inverse(self.q, self.p)) self.assertRaises(ValueError, self.rsa.construct, tup)
Example #9
Source File: test_RSA.py From FODI with GNU General Public License v3.0 | 5 votes |
def setUp(self): global RSA, Random, bytes_to_long from Crypto.PublicKey import RSA from Crypto import Random from Crypto.Util.number import bytes_to_long, inverse self.n = bytes_to_long(a2b_hex(self.modulus)) self.p = bytes_to_long(a2b_hex(self.prime_factor)) # Compute q, d, and u from n, e, and p self.q = self.n // self.p self.d = inverse(self.e, (self.p-1)*(self.q-1)) self.u = inverse(self.p, self.q) # u = e**-1 (mod q) self.rsa = RSA
Example #10
Source File: curve25519.py From iChainbreaker with GNU General Public License v2.0 | 5 votes |
def curve25519(secret, basepoint): a = ord(secret[0]) a &= 248 b = ord(secret[31]) b &= 127 b |= 64 s = chr(a) + secret[1:-1] + chr(b) s = number.bytes_to_long(s[::-1]) basepoint = number.bytes_to_long(basepoint[::-1]) x, z = curve25519_mult(s, basepoint) zmone = number.inverse(z, CURVE_P) z = x * zmone % CURVE_P return number.long_to_bytes(z)[::-1]
Example #11
Source File: rsa_crack.py From hacker-scripts with MIT License | 5 votes |
def crack(n, e, encrypted_data): print('n: %s' % n) print('e: %s' % e) success, p, q = prime_factor(n) # success, p, q = True, 323067951880962860113901833788589140869, 263074551335953569706833061753492041353 if success: d = inverse(e, (p - 1) * (q - 1)) print('d: %s' % d) rsa = RSA.construct((n, e, d)) plain = rsa.decrypt(encrypted_data) print(plain)
Example #12
Source File: rsa_crack2.py From hacker-scripts with MIT License | 5 votes |
def crack(n, e, encrypted_data): print('n: %s' % n) print('e: %s' % e) success, p, q = prime_factor(n) # success, p, q = True, 323067951880962860113901833788589140869, 263074551335953569706833061753492041353 if success: d = inverse(e, (p - 1) * (q - 1)) print('d: %s' % d) rsa = RSA.construct((n, e, d)) plain = rsa.decrypt(encrypted_data) print(plain)
Example #13
Source File: example.py From Crypton with MIT License | 5 votes |
def _decrypt(ciphertext, privkey): """ Decrypt ciphertext using ElGamal Encryption System :Parameters: ciphertext : int/long tuple Ciphertext of ElGamal encrypted plaintext privkey : instance of `PrivateKey` class Receiver's private key used for decryption :Variables: g : int/long Base point for modular exponentiation. p : int/long Modulus for modular exponentiation. Should be a safe prime. q : int/long Order of group generated by p and equals p-1 c1, c2: int/long Ciphertext pair x : int/long Receiver's private key, should be kept secret. s : int/long Shared secret """ c1, c2 = ciphertext g = privkey.g p = privkey.p x = privkey.x s = pow(c1, x, p) m = (c2*inverse(s, p)) % p return m
Example #14
Source File: test_RSA.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def _exercise_primitive(self, rsaObj): # Since we're using a randomly-generated key, we can't check the test # vector, but we can make sure encryption and decryption are inverse # operations. ciphertext = a2b_hex(self.ciphertext) # Test decryption plaintext = rsaObj.decrypt((ciphertext,)) # Test encryption (2 arguments) (new_ciphertext2,) = rsaObj.encrypt(plaintext, b("")) self.assertEqual(b2a_hex(ciphertext), b2a_hex(new_ciphertext2)) # Test blinded decryption blinding_factor = Random.new().read(len(ciphertext)-1) blinded_ctext = rsaObj.blind(ciphertext, blinding_factor) blinded_ptext = rsaObj.decrypt((blinded_ctext,)) unblinded_plaintext = rsaObj.unblind(blinded_ptext, blinding_factor) self.assertEqual(b2a_hex(plaintext), b2a_hex(unblinded_plaintext)) # Test signing (2 arguments) signature2 = rsaObj.sign(ciphertext, b("")) self.assertEqual((bytes_to_long(plaintext),), signature2) # Test verification self.assertEqual(1, rsaObj.verify(ciphertext, (bytes_to_long(plaintext),)))
Example #15
Source File: test_RSA.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def setUp(self): global RSA, Random, bytes_to_long from Crypto.PublicKey import RSA from Crypto import Random from Crypto.Util.number import bytes_to_long, inverse self.n = bytes_to_long(a2b_hex(self.modulus)) self.p = bytes_to_long(a2b_hex(self.prime_factor)) # Compute q, d, and u from n, e, and p self.q = divmod(self.n, self.p)[0] self.d = inverse(self.e, (self.p-1)*(self.q-1)) self.u = inverse(self.p, self.q) # u = e**-1 (mod q) self.rsa = RSA
Example #16
Source File: _slowmath.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def _unblind(self, m, r): # compute m / r (mod n) return inverse(r, self.n) * m % self.n
Example #17
Source File: ElGamal.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def _sign(self, M, K): if (not hasattr(self, 'x')): raise TypeError('Private key not available in this object') p1=self.p-1 if (GCD(K, p1)!=1): raise ValueError('Bad K value: GCD(K,p-1)!=1') a=pow(self.g, K, self.p) t=(M-self.x*a) % p1 while t<0: t=t+p1 b=(t*inverse(K, p1)) % p1 return (a, b)
Example #18
Source File: ElGamal.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def _decrypt(self, M): if (not hasattr(self, 'x')): raise TypeError('Private key not available in this object') ax=pow(M[0], self.x, self.p) plaintext=(M[1] * inverse(ax, self.p ) ) % self.p return plaintext
Example #19
Source File: modern.py From featherduster with BSD 3-Clause "New" or "Revised" License | 5 votes |
def dsa_repeated_nonce_attack(r,msg1,s1,msg2,s2,n,verbose=False): ''' Recover k (nonce) and Da (private signing key) from two DSA or ECDSA signed messages with identical k values Takes the following arguments: string: r (r value of signatures) string: msg1 (first message) string: s1 (s value of first signature) string: msg2 (second message) string: s2 (s value of second signature) long: n (curve order for ECDSA or modulus (q parameter) for DSA) adapted from code by Antonio Bianchi (antoniob@cs.ucsb.edu) <http://antonio-bc.blogspot.com/2013/12/mathconsole-ictf-2013-writeup.html> ''' r = string_to_long(r) s1 = string_to_long(s1) s2 = string_to_long(s2) # convert messages to sha1 hash as number z1 = string_to_long(SHA.new(msg1).digest()) z2 = string_to_long(SHA.new(msg2).digest()) sdiff_inv = number.inverse(((s1-s2)%n),n) k = ( ((z1-z2)%n) * sdiff_inv) % n r_inv = number.inverse(r,n) da = (((((s1*k) %n) -z1) %n) * r_inv) % n if verbose: print "Recovered k:" + hex(k) print "Recovered Da: " + hex(da) return (k, da)
Example #20
Source File: modern.py From featherduster with BSD 3-Clause "New" or "Revised" License | 5 votes |
def lcg_prev_states(states, num_states=5, a=None, c=None, m=None): ''' Given the current state of an LCG, return the previous states in sequence. Currently, the modulus must be known. Other parameters can be recovered given enough sequential states. states - (list of ints) Known sequential states from the LCG. num_states - (int) The number of past states to generate. a - (int) The multiplier for the LCG. c - (int) The addend for the LCG. m - (int) The modulus for the LCG. ''' if not all([a,c,m]): parameters = lcg_recover_parameters(states,a,c,m) if parameters == False: return False else: (a,c,m) = parameters current_state = states[0] prev_states = [] for i in range(num_states): current_state = (((current_state - c) % m) * number.inverse(a, m)) % m prev_states.insert(0,current_state) return prev_states
Example #21
Source File: helpers.py From featherduster with BSD 3-Clause "New" or "Revised" License | 5 votes |
def derive_d_from_pqe(p,q,e): ''' Given p, q, and e from factored RSA modulus, derive the private component d p - The first of the two factors of the modulus q - The second of the two factors of the modulus e - The public exponent ''' return long(number.inverse(e,(p-1)*(q-1)))
Example #22
Source File: helpers.py From featherduster with BSD 3-Clause "New" or "Revised" License | 5 votes |
def rsa_unblind(message, randint, modulus): """ Return message RSA-unblinded with integer randint for a keypair with the provided modulus. """ return number.inverse(randint, modulus) * message % modulus
Example #23
Source File: test_RSA.py From earthengine with MIT License | 5 votes |
def setUp(self): global RSA, Random, bytes_to_long from Crypto.PublicKey import RSA from Crypto import Random from Crypto.Util.number import bytes_to_long, inverse self.n = bytes_to_long(a2b_hex(self.modulus)) self.p = bytes_to_long(a2b_hex(self.prime_factor)) # Compute q, d, and u from n, e, and p self.q = divmod(self.n, self.p)[0] self.d = inverse(self.e, (self.p-1)*(self.q-1)) self.u = inverse(self.p, self.q) # u = e**-1 (mod q) self.rsa = RSA
Example #24
Source File: _slowmath.py From earthengine with MIT License | 5 votes |
def _unblind(self, m, r): # compute m / r (mod n) return inverse(r, self.n) * m % self.n
Example #25
Source File: ElGamal.py From earthengine with MIT License | 5 votes |
def _decrypt(self, M): if (not hasattr(self, 'x')): raise TypeError('Private key not available in this object') ax=pow(M[0], self.x, self.p) plaintext=(M[1] * inverse(ax, self.p ) ) % self.p return plaintext
Example #26
Source File: _slowmath.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 4 votes |
def rsa_construct(n, e, d=None, p=None, q=None, u=None): """Construct an RSAKey object""" assert isinstance(n, long) assert isinstance(e, long) assert isinstance(d, (long, type(None))) assert isinstance(p, (long, type(None))) assert isinstance(q, (long, type(None))) assert isinstance(u, (long, 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
Example #27
Source File: RSA.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 4 votes |
def _importKeyDER(self, externKey): """Import an RSA key (public or private half), encoded in DER form.""" try: der = DerSequence() der.decode(externKey, True) # 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(inverse(der[4],der[5])) # Add p^{-1} mod q del der[0] # Remove version return self.construct(der[:]) # Keep on trying PKCS#1, but now for a public key if len(der)==2: # The DER object is an RSAPublicKey SEQUENCE with two elements if der.hasOnlyInts(): return self.construct(der[:]) # The DER object is a SubjectPublicKeyInfo SEQUENCE with two elements: # an 'algorithm' (or 'algorithmIdentifier') SEQUENCE and a 'subjectPublicKey' BIT STRING. # 'algorithm' takes the value given a few lines above. # 'subjectPublicKey' encapsulates the actual ASN.1 RSAPublicKey element. if der[0]==algorithmIdentifier: bitmap = DerObject() bitmap.decode(der[1], True) if bitmap.isType('BIT STRING') and bord(bitmap.payload[0])==0x00: der.decode(bitmap.payload[1:], True) if len(der)==2 and der.hasOnlyInts(): return self.construct(der[:]) # Try unencrypted PKCS#8 if der[0]==0: # The second element in the SEQUENCE is algorithmIdentifier. # It must say RSA (see above for description). if der[1]==algorithmIdentifier: privateKey = DerObject() privateKey.decode(der[2], True) if privateKey.isType('OCTET STRING'): return self._importKeyDER(privateKey.payload) except ValueError, IndexError: pass
Example #28
Source File: lsbitoracle-variant.py From Crypton with MIT License | 4 votes |
def lsbitoracle_variant(flag_enc, _decrypt, e, N, len_flag): """ Function implementing a variant of LSBit Oracle Attack Time complexity is O(len_flag) where len_flag is the length of the flag in bits :parameters: flag_enc : str Ciphertext we want to decrypt _decrypt : function Function interacting with the remote service for decryption e : int/long Public Key exponent N : long Public Key modulus len_flag : int Length of plaintext in bits (for eg. 128 bit long flag) Function returns -1 in case of any Exception, with appropriate error message """ output = _decrypt(flag_enc) assert output == "\x01" or output == "\x00" flag = bin(ord(output))[2:] for i in range(1, len_flag): temp_cal = 2**i try: assert GCD(temp_cal, N) == 1 except: print "[-] GCD(2**i, N) != 1, obtained one factor of N successfully" return -1 inv = inverse(temp_cal, N) chosen_ct = long_to_bytes((bytes_to_long(flag_enc)*pow(inv, e, N)) % N) output = _decrypt(chosen_ct) try: assert output == "\x01" or output == "\x00" except: print "[-] Unusual output obtained. Exiting..." return -1 # Compute i-th bit of plaintext based on the output obtained above flag_char = (ord(output) - (int(flag, 2)*inv) % N) % 2 # Prepend i-th bit calculated to the plaintext string flag = str(flag_char) + flag if len(flag) % 8 == 0: print "Plaintext recovered till now: ", long_to_bytes(int(flag, 2)) return long_to_bytes(int(flag, 2))
Example #29
Source File: test_RSA.py From earthengine with MIT License | 4 votes |
def _exercise_primitive(self, rsaObj): # Since we're using a randomly-generated key, we can't check the test # vector, but we can make sure encryption and decryption are inverse # operations. ciphertext = a2b_hex(self.ciphertext) # Test decryption plaintext = rsaObj.decrypt((ciphertext,)) # Test encryption (2 arguments) (new_ciphertext2,) = rsaObj.encrypt(plaintext, b("")) self.assertEqual(b2a_hex(ciphertext), b2a_hex(new_ciphertext2)) # Test blinded decryption blinding_factor = Random.new().read(len(ciphertext)-1) blinded_ctext = rsaObj.blind(ciphertext, blinding_factor) blinded_ptext = rsaObj.decrypt((blinded_ctext,)) unblinded_plaintext = rsaObj.unblind(blinded_ptext, blinding_factor) self.assertEqual(b2a_hex(plaintext), b2a_hex(unblinded_plaintext)) # Test signing (2 arguments) signature2 = rsaObj.sign(ciphertext, b("")) self.assertEqual((bytes_to_long(plaintext),), signature2) # Test verification self.assertEqual(1, rsaObj.verify(ciphertext, (bytes_to_long(plaintext),)))
Example #30
Source File: _slowmath.py From earthengine with MIT License | 4 votes |
def rsa_construct(n, e, d=None, p=None, q=None, u=None): """Construct an RSAKey object""" assert isinstance(n, long) assert isinstance(e, long) assert isinstance(d, (long, type(None))) assert isinstance(p, (long, type(None))) assert isinstance(q, (long, type(None))) assert isinstance(u, (long, 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