def _common_module_attack(n, e_b, d_b, e_a): N = (e_b * d_b) - 1 # 1) N <- (e_b*d_b)-1 f, s = get_f_s_from_N(N) # N = (2^f)*s a = randint(1, n - 1) # 2) a <- rand (Z/nZ) b = pow(int(a), int(s), int(n)) # b <- a^s (mod n) print("b = ", b) l_and_t_found = False print("start finding l") l = find_l(b, int(n)) while (not l_and_t_found): # 3) b^(2^l) = 1 (mod n) # if (b^(2^(l-1)) = -1 (mod n)) pow_b = pow(2, l - 1) # new rand a, go to 2) if (pow(b, pow_b, n) == -1): # else a = randint(1, n - 1) # t <- b^(2^(l-1)) (mod n) b = pow(a, s, n) l = find_l(b) else: t = pow(b, pow_b, n) l_and_t_found = True p = GCD(t + 1, n) # 4) p <- gcd(t+1,n) q = GCD(t - 1, n) # q <- gcd(t-1,n) f_n_2 = (p - 1) * (q - 1) d_a = inverse(e_a, f_n_2) while (d_a == d_b): d_a = inverse(e_b, f_n_2) if d_b != d_a: print("Attack for common module: Success") else: print("Attack for common module: Failed")
def recover_nonce_reuse(self, other): assert (self.pubkey.q == other.pubkey.q) assert (self.sig.r == other.sig.r) # reused *k* implies same *r* self.k = (self.h - other.h) * inverse(self.sig.s - other.sig.s, self.pubkey.q) % self.pubkey.q self.x = ((self.k * self.sig.s - self.h) * inverse(self.sig.r, self.pubkey.q)) % self.pubkey.q # other.k, other.x = self.k, self.x # update other object as well? return self
def setUp(self): global RSA, Random, bytes_to_long from Cryptodome.PublicKey import RSA from Cryptodome import Random from Cryptodome.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
def test_construct_bad_key6(self): tup = (self.n, self.e, self.d, self.p, self.q, 10L) self.assertRaises(ValueError, self.rsa.construct, tup) from Cryptodome.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)
def decrypt(self, cipher): """ :type cipher long :param cipher: 密文 :return: """ cipher = self.encoding_2_long(cipher, self.cipher_encoding) if self.d is not None: d = self.d else: d = inverse(self.e, (self.p - 1) * (self.q - 1)) if self.n is not None: n = self.n else: n = self.p * self.q rsa = RSA.construct((n, self.e, d)) if self.padding == 'PKCS1_OAEP': rsa = PKCS1_OAEP.new(rsa) plain = rsa.decrypt(long_to_bytes(cipher)) elif self.padding == 'PKCS1_v1_5': rsa = PKCS1_v1_5.new(rsa) plain = rsa.decrypt(long_to_bytes(cipher), True) else: plain = pow(cipher, d, n) return self.long_2_encoding(plain, self.plain_encoding) plain = self.long_2_encoding(bytes_to_long(plain), self.plain_encoding) return plain
def uncrypt(self, block): """ La fonction de déchiffrement""" byte_size = self.bit_size//8 if len(block) == 4*byte_size: b_B1 = block[0:byte_size] b_B2 = block[byte_size:2*byte_size] b_c = block[2*byte_size:3*byte_size] b_v = block[3*byte_size:4*byte_size] B1 = int.from_bytes(b_B1, sys.byteorder) B2 = int.from_bytes(b_B2, sys.byteorder) c = int.from_bytes(b_c, sys.byteorder) v = int.from_bytes(b_v, sys.byteorder) # vérification de v p = self.p x1, x2, y1, y2 = self.x1, self.x2, self.y1, self.y2 H = self.hashFunction((B1 + B2 + c) % p) v_bis = (pow(B1, x1, p) * pow(B2, x2, p) * pow(pow(B1, y1, p) * pow(B2, y2, p), H, p)) % p if v_bis != v: raise ValueError('Le message a été altéré après le chiffrement') # déchiffrement m = (inverse(pow(B1, self.w, p), p) * c) % p m = m.to_bytes(byte_size, sys.byteorder) return unpad(m, byte_size, 'iso7816') else: raise ValueError("Le block ne possède pas la bonne taille pour le déchiffrement")
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 Cryptodome.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)
def copper_rsa_lattice(): """ Encryption: import random base = random.getrandbits(2048) p = next_prime(base + random.getrandbits(256)) q = next_prime(base + random.getrandbits(256)) n = p * q e = 65537 print("e = ", e) print("n = ", n) c = power_mod(m, e, n) print("c = ", c) Output: """ from Cryptodome.Util import number e = 65537 n = 8281850967132278399574272688766937486036646313403007679588335903785669628431708760927341727806006769095252325575815709840401878674105658204057327337750902945521512357960818523078486774689928139816732080923197367563639383252762498921096166065153092144335239373370093976823925031794323976150363874930075228846801224430767428594024165529140949082062667410186456029480046489969338885725614510660737026927443934115006027747874368836800022473917576424175601374800697491622086825964475396316066082109998646438504664272000556702241576240616765962934452557847306066736505798267513078073147161755828577875047115978481485076227911405625234425533967247248864837854031634968764570599279385827285321806293661331225163255461894680337693227417748934924109356565823327149859245521513696171473417470936260563397398387972467438182651142096935931112668743912944902147582538985769095457203775208567489073198557073226907349118348902079942096374377432431441166710584381655348979330535397040250376989291669788189409825278457889980676574146044704329826483808929549888234303934178478274711686806257841293265249466735277673158607466360053037971774844824065612178793324128914371112619033111301900922374201703477207948412866443213080633623441392016518823291181 c = 6407923537926201847312357068295079879508779752068254604904486842729636773279241546432035102141932853761974844472828552921133743850412718722424893044377874567625621282274625365299685502104113862870672461666586814138206797733946319875258776059721304226419810313489197076949529322847815009706727586961448584443159011118432142946962961532154723891985416387650240762711716865116844837968079333914181751979527853152286708153252001832721723040664452442266930832118353632114958540067674924812749763008217133300059446967170825813909142247660230309955433005706793802514554628379255160648976960069078223370104177403453404917998945232459801324103878906593528309460372271638119657797804398399482025063414403804134607772871958848100256643503372624214762343403925077455660522664025602043433142314759978192969519687720668535544914589329155338178120703060384042066182354031274600184116143293639032906542194564776766076911767759167772137229504115598174156646085123675283692418970988032320780636742598466655712520383055569607154074137271584433653335176877094399371749081016317705026349554938167377640856287458145646649292278971980553895419112860061073864077521131958519819285117031990498977039003918710661660868949818362940359852436185282868088342132 p = 2877820523787450925749443223409676535526103461002156158445828224293671401993991478543020287097392331073352851877283061169200661485601861126177989029099279726556037706157577055235829106587295127330817726845862915284936240880512882371822435354503703582818585826639860414460347276612398615213473473435297607044419660432857760267782763215613805061134548930946450808892523918406477350229326879718460875896139320212120566207583969498664502640043503068067423704342779684140776844591504545219651693576024138161226306265777913216051021635043708034933142150577361241126706252795462441428424206966514776010058207246337809108763 q = 2877820523787450925749443223409676535526103461002156158445828224293671401993991478543020287097392331073352851877283061169200661485601861126177989029099279726556037706157577055235829106587295127330817726845862915284936240880512882371822435354503703582818585826639860414460347276612398615213473473435297607044419660432857760267782763215613805061134548930946450808892523918406477350229326879718460875896139320212120566207583969498664502640043503068067423704342779684140776844591504545219651693576024138161226306265777913216051021635043708034966478921186010140653104995611058414645030602000549187384764408555794028217687 # factorized n from http://factordb.com phi = (p - 1) * (q - 1) d = number.inverse(e, phi) print(number.long_to_bytes(pow(c, d, n)))
def attack(c: bytes): e, n = K B = 1 << (8 * (k - 2)) # Init. print('Step 1......', end=' ', flush=True) if oracle(c): # m was already padded before encryption s0 = 1 else: # Step 1 s0 = random.randint(0, n - 1) while not oracle(c * pow(s0, e, n)): s0 = random.randint(0, n - 1) M = [(2 * B, 3 * B - 1)] c0 = (c * pow(s0, e, n)) % n i = 1 print('ok') # Step 2.a print('Step 2a.....', end=' ', flush=True) s = ceil_div(n, 3 * B) while not oracle(c0 * pow(s, e, n)): s += 1 print('ok') while True: print(f'Steps 2b-4... {i}', end='\r', flush=True) if len(M) > 1: # Step 2.b s += 1 while not oracle(c0 * pow(s, e, n)): s += 1 else: # Step 2.c a, b = M[0] r = ceil_div(2 * (b * s - 2 * B), n) # as in the article, #r = ceil_div(2*(b*s-B), n) # or corrected typo? s = ceil_div(2 * B + r * n, b) while not oracle(c0 * pow(s, e, n)): s += 1 if a * s >= 3 * B + r * n: r += 1 s = ceil_div(2 * B + r * n, b) # Step 3 Mupd = [] for a, b in M: r = ceil_div(a * s - 3 * B + 1, n) while n * r <= b * s - 2 * B: a1 = max(a, ceil_div(2 * B + r * n, s)) b1 = min(b, (3 * B - 1 + r * n) // s) if a1 <= b1: Mupd.append((a1, b1)) r += 1 M = merge_intervals(Mupd) # Step 4 if len(M) == 1 and M[0][0] == M[0][1]: return (M[0][0] * inverse(s0, n)) % n i += 1
def rsa_crt_multiprime(y): phi = (p - 1) * (q - 1) * (r - 1) d = pow(e, -1, phi) b1 = pow(y % p, d % (p - 1), p) b2 = pow(y % q, d % (q - 1), q) b3 = pow(y % r, d % (r - 1), r) x1 = b1 % p c = ((b2 - x1) * inverse(p, q)) % q x2 = x1 + p * c d = ((b3 - x2) * inverse(p * q, r)) % r x3 = x2 + p * q * d return x3
def calculate_prediction(self, encrypted_nom, encrypted_denom): plain_nom = encrypted_nom[1] * inverse( pow(encrypted_nom[0], self.privElgamalKey, self.p), self.p) plain_denom = encrypted_denom[1] * inverse( pow(encrypted_denom[0], self.privElgamalKey, self.p), self.p) #print(self.boundedDiscreteLog(plain_nom % self.p)) #print(self.boundedDiscreteLog(plain_denom % self.p)) nom = self.boundedDiscreteLog(plain_nom % self.p) denom = self.boundedDiscreteLog(plain_denom % self.p) print("Nom", nom) print("Denom", denom) if denom == 0: prediction = 0 else: prediction = nom / denom return prediction
def calculateSimMat(self): self.genElgamalKeys() n = len(self.user_list) sim_round1_m = [] for i in range(n): sim_round1_m.append(self.user_list[i].sim_round1_all( self.m, self.avg_ratings)) print("Round 1 User: "******"Round 2 User: "******"Round2 Done") for i in range(self.m): temp_zero = [] for j in range(self.m): temp_zero.append(0) decrypt_pairwise_m.append(temp_zero) decrypt_denom.append(0) progress = 0 for i in range(self.m): for j in range(self.m): base = 1 for k in range(n): base = base * round2_m[k][i][j] % self.p progress += 1 #decrypt_pairwise_m[i][j] = pairwise_mults[i][j][1] * inverse(base, self.p) % self.p decrypt_pairwise_m[i][j] = self.boundedDiscreteLog( pairwise_mults[i][j][1] * inverse(base, self.p) % self.p) #print("Decrypt i: ", i, " j: ", j, " Done!") print("Progress: %", 100 * float(progress) / (self.m * self.m * n)) decrypt_denom[i] = decrypt_pairwise_m[i][i] result_matrix = [] for i in range(self.m): sim_vector = [] for j in range(self.m): sim_vector.append( int( self.getSim(decrypt_pairwise_m[i][j], decrypt_denom[i], decrypt_denom[j]) * 100)) result_matrix.append(sim_vector) #print(result_matrix) self.simMat = result_matrix
def gen_key(prime_size = 1024): p = getPrime(prime_size) q = getPrime(prime_size) n = p * q g = n + 1 phi = (p - 1) * (q - 1) l = phi mu = inverse(phi, n) return (n, g), (l, mu)
def rsa_crt_multipower(y): phi = p * (p - 1) * (q - 1) d = pow(e, -1, phi) p2 = p * p x0 = pow(y % p, d % (p - 1), p) xq = pow(y % q, d % (q - 1), q) first = (y - pow(x0, e, p2)) // p second = inverse(e * pow(x0, e - 1, p), p) x1 = (first * second) % p xp2 = x1 * p + x0 sol1 = xp2 % p2 c = ((xq - sol1) * inverse(p2, q)) % q sol2 = sol1 + p2 * c return sol2
def __init__(self): self.e = 3 self.p = getStrongPrime(512, e=self.e) self.q = getStrongPrime(512, e=self.e) self.n = self.p * self.q self.phi = (self.p - 1) * (self.q - 1) self.d = inverse(self.e, self.phi) ## generate secret seed self.seed = pow(1 << 1023, self.e, self.n) self.seed = long_to_bytes(self.seed)
def __decrypt_block(self, blob, p, q, block_size, n): c = bytes_to_int(blob) m_p = sqrt_mod(c, p) m_q = sqrt_mod(c, q) q_inv = number.inverse(q, p) p_inv = number.inverse(p, q) m = [(m_p * q * q_inv + m_q * p * p_inv) % n, (m_p * q * q_inv - m_q * p * p_inv) % n] m += [n - m[0], n - m[1]] for block in m: bytes_arr = int_to_bytes(block) if bytes_to_int(bytes_arr[:len(Rabin._PADDING)]) == bytes_to_int( Rabin._PADDING): data_len = bytes_arr[len(Rabin._PADDING):len(Rabin._PADDING) + byte_length(block_size)] data_len = bytes_to_int(data_len) return bytes_arr[-1 - data_len:-1] raise ValueError("Incorrect ciphertext format")
def rsa_twins(): from Cryptodome.Util import number n = 14783703403657671882600600446061886156235531325852194800287001788765221084107631153330658325830443132164971084137462046607458019775851952933254941568056899 e = 65537 c = 684151956678815994103733261966890872908254340972007896833477109225858676207046453897176861126186570268646592844185948487733725335274498844684380516667587 # factorized n from http://factordb.com p = 121588253559534573498320028934517990374721243335397811413129137253981502291629 q = 121588253559534573498320028934517990374721243335397811413129137253981502291631 phi = (p - 1) * (q - 1) d = number.inverse(e, phi) print(number.long_to_bytes(pow(c, d, n)))
def _generate_a(r): e = 0 d = 0 some = True while (some == True): e = randint(1, r - 1) if (GCD(e, r) == 1): d = inverse(e, r) if ((e * d) % r == 1): some = False break print("a = ", e) print("a_1 = ", d) return e, d
def decrypt(grps, e): for grp in combinations(zip(grps['n'], grps['c']), e): N = 1 for x in grp: N *= x[0] M = 0 for x in grp: M += x[1] * number.inverse(N // x[0], x[0]) * (N // x[0]) M %= N m, exact = gmpy.root(M, e) if exact: print(number.long_to_bytes(m))
def decrypt(self, cipher): """ :type cipher long :param cipher: 密文 :return: """ cipher = self.encoding_2_long(cipher, self.cipher_encoding) if self.d is not None: d = self.d else: d = inverse(self.e, (self.p - 1) * (self.q - 1)) if self.n is not None: n = self.n elif self.p is not None and self.q is not None: n = self.p * self.q else: return '!!!error: n is empty!!!' # (N,e)是公钥,(N,d)是私钥 if self.encrypt_method == 'private-key-encrypt': n, e, d = n, d, self.e elif self.encrypt_method == 'public-key-encrypt': n, e, d = n, self.e, d else: return '!!!wrong encrypt_method!!!' rsa = RSA.construct((n, e, d)) if self.padding == 'PKCS1_OAEP': rsa = PKCS1_OAEP.new(rsa) plain = rsa.decrypt(long_to_bytes(cipher)) elif self.padding == 'PKCS1_v1_5_Java': rsa = PKCS1_v1_5_Java_Cipher(rsa, Random.get_random_bytes) # 第二个参数 False,表示出错时会返回 False,plain 的值将为 False plain = rsa.decrypt(long_to_bytes(cipher), False) if plain is False: return '!!!error: decrypt error!!!' elif self.padding == 'PKCS1_v1_5': rsa = PKCS1_v1_5.new(rsa) # 第二个参数 False,表示出错时会返回 False,plain 的值将为 False plain = rsa.decrypt(long_to_bytes(cipher), False) if plain is False: return '!!!error: decrypt error!!!' else: plain = pow(cipher, d, n) return self.long_2_encoding(plain, self.plain_encoding) plain = self.long_2_encoding(bytes_to_long(plain), self.plain_encoding) return plain
def parse_PRIK(chunk, encryption_key): """Parse PRIK chunk which contains private RSA key""" decrypted = decode_aes256('cbc', encryption_key[:16], decode_hex(chunk.payload), encryption_key) hex_key = re.match(br'^LastPassPrivateKey<(?P<hex_key>.*)>LastPassPrivateKey$', decrypted).group('hex_key') rsa_key = RSA.importKey(decode_hex(hex_key)) rsa_key.dmp1 = rsa_key.d % (rsa_key.p - 1) rsa_key.dmq1 = rsa_key.d % (rsa_key.q - 1) rsa_key.iqmp = number.inverse(rsa_key.q, rsa_key.p) return rsa_key
def good_parameters(): p, q = getPrimePair() n = p * q f_n = (p - 1) * (q - 1) while (True): e = randint(1, f_n - 1) if (GCD(e, f_n) == 1): d = inverse(e, f_n) if 36 * pow(d, 4) > n: break print("p = {}".format(p)) print("q = {}".format(q)) print("n = {}".format(n)) print("e = {}".format(e)) print("d = {}".format(d))
def gen_key(size=1 << 10): e = 3 # we always want e = 3 here n = 0 while n.bit_length() < size: p = getPrime(size >> 1) while (p - 1) % e == 0: # gcd(e, p-1) != 1 p = getPrime(size >> 1) q = getPrime(size >> 1) while (q - 1) % e == 0: # gcd(e, q-1) != 1 q = getPrime(size >> 1) n = p * q phi = (p - 1) * (q - 1) #d = pow(e, -1, phi) d = inverse(e, phi) K = PubKey(e, n) k = PrivKey(d, n) return (k, K)
def keygen(security_param = 2048): p = number.getPrime(security_param // 2) q = number.getPrime(security_param // 2) n = p*q phi = (p - 1)*(q - 1) e = randint(0, phi) while number.GCD(e, phi) != 1: e = randint(0, phi) key_coder = RsaKeyCoder() public_key = key_coder.encode_public_key(e, n) key_encryptor = KeyEncryptor.get_instance() d = number.inverse(e, phi) private_key = key_encryptor.encrypt(key_coder.encode_private_key(d, n)) return public_key, private_key
def encrypt(self, plain): """ :type plain long :param plain: 明文 :return: """ plain = self.encoding_2_long(plain, self.plain_encoding) # (N,e)是公钥,(N,d)是私钥 if self.encrypt_method == 'public-key-encrypt': n, e = self.n, self.e elif self.encrypt_method == 'private-key-encrypt': if self.d is not None: d = self.d else: d = inverse(self.e, (self.p - 1) * (self.q - 1)) if self.n is not None: n = self.n else: n = self.p * self.q n, e = n, d else: return '!!!wrong encrypt_method!!!' rsa = RSA.construct((n, e,)) # 最佳非对称加密填充(OAEP) if self.padding == 'PKCS1_OAEP': rsa = PKCS1_OAEP.new(rsa) cipher = rsa.encrypt(long_to_bytes(plain)) elif self.padding == 'PKCS1_v1_5_Java': rsa = PKCS1_v1_5_Java_Cipher(rsa, Random.get_random_bytes) cipher = rsa.encrypt(long_to_bytes(plain)) elif self.padding == 'PKCS1_v1_5': rsa = PKCS1_v1_5.new(rsa) cipher = rsa.encrypt(long_to_bytes(plain)) else: cipher = pow(plain, e, n) return self.long_2_encoding(cipher, self.cipher_encoding) cipher = self.long_2_encoding(bytes_to_long(cipher), self.cipher_encoding) return cipher
class ImportKeyTests(unittest.TestCase): # 512-bit RSA key generated with openssl rsaKeyPEM = '''-----BEGIN RSA PRIVATE KEY----- MIIBOwIBAAJBAL8eJ5AKoIsjURpcEoGubZMxLD7+kT+TLr7UkvEtFrRhDDKMtuII q19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQJACUSDEp8RTe32ftq8IwG8 Wojl5mAd1wFiIOrZ/Uv8b963WJOJiuQcVN29vxU5+My9GPZ7RA3hrDBEAoHUDPrI OQIhAPIPLz4dphiD9imAkivY31Rc5AfHJiQRA7XixTcjEkojAiEAyh/pJHks/Mlr +rdPNEpotBjfV4M4BkgGAA/ipcmaAjcCIQCHvhwwKVBLzzTscT2HeUdEeBMoiXXK JACAr3sJQJGxIQIgarRp+m1WSKV1MciwMaTOnbU7wxFs9DP1pva76lYBzgUCIQC9 n0CnZCJ6IZYqSt0H5N7+Q+2Ro64nuwV/OSQfM6sBwQ== -----END RSA PRIVATE KEY-----''' # As above, but this is actually an unencrypted PKCS#8 key rsaKeyPEM8 = '''-----BEGIN PRIVATE KEY----- MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAvx4nkAqgiyNRGlwS ga5tkzEsPv6RP5MuvtSS8S0WtGEMMoy24girX0WsvilQgzKY8xIsGfeEkt7fQPDj wZAzhQIDAQABAkAJRIMSnxFN7fZ+2rwjAbxaiOXmYB3XAWIg6tn9S/xv3rdYk4mK 5BxU3b2/FTn4zL0Y9ntEDeGsMEQCgdQM+sg5AiEA8g8vPh2mGIP2KYCSK9jfVFzk B8cmJBEDteLFNyMSSiMCIQDKH+kkeSz8yWv6t080Smi0GN9XgzgGSAYAD+KlyZoC NwIhAIe+HDApUEvPNOxxPYd5R0R4EyiJdcokAICvewlAkbEhAiBqtGn6bVZIpXUx yLAxpM6dtTvDEWz0M/Wm9rvqVgHOBQIhAL2fQKdkInohlipK3Qfk3v5D7ZGjrie7 BX85JB8zqwHB -----END PRIVATE KEY-----''' # The same RSA private key as in rsaKeyPEM, but now encrypted rsaKeyEncryptedPEM=( # PEM encryption # With DES and passphrase 'test' ('test', '''-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-CBC,AF8F9A40BD2FA2FC Ckl9ex1kaVEWhYC2QBmfaF+YPiR4NFkRXA7nj3dcnuFEzBnY5XULupqQpQI3qbfA u8GYS7+b3toWWiHZivHbAAUBPDIZG9hKDyB9Sq2VMARGsX1yW1zhNvZLIiVJzUHs C6NxQ1IJWOXzTew/xM2I26kPwHIvadq+/VaT8gLQdjdH0jOiVNaevjWnLgrn1mLP BCNRMdcexozWtAFNNqSzfW58MJL2OdMi21ED184EFytIc1BlB+FZiGZduwKGuaKy 9bMbdb/1PSvsSzPsqW7KSSrTw6MgJAFJg6lzIYvR5F4poTVBxwBX3+EyEmShiaNY IRX3TgQI0IjrVuLmvlZKbGWP18FXj7I7k9tSsNOOzllTTdq3ny5vgM3A+ynfAaxp dysKznQ6P+IoqML1WxAID4aGRMWka+uArOJ148Rbj9s= -----END RSA PRIVATE KEY-----'''), # PKCS8 encryption ('winter', '''-----BEGIN ENCRYPTED PRIVATE KEY----- MIIBpjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIeZIsbW3O+JcCAggA MBQGCCqGSIb3DQMHBAgSM2p0D8FilgSCAWBhFyP2tiGKVpGj3mO8qIBzinU60ApR 3unvP+N6j7LVgnV2lFGaXbJ6a1PbQXe+2D6DUyBLo8EMXrKKVLqOMGkFMHc0UaV6 R6MmrsRDrbOqdpTuVRW+NVd5J9kQQh4xnfU/QrcPPt7vpJvSf4GzG0n666Ki50OV M/feuVlIiyGXY6UWdVDpcOV72cq02eNUs/1JWdh2uEBvA9fCL0c07RnMrdT+CbJQ NjJ7f8ULtp7xvR9O3Al/yJ4Wv3i4VxF1f3MCXzhlUD4I0ONlr0kJWgeQ80q/cWhw ntvgJwnCn2XR1h6LA8Wp+0ghDTsL2NhJpWd78zClGhyU4r3hqu1XDjoXa7YCXCix jCV15+ViDJzlNCwg+W6lRg18sSLkCT7alviIE0U5tHc6UPbbHwT5QqAxAABaP+nZ CGqJGyiwBzrKebjgSm/KRd4C91XqcsysyH2kKPfT51MLAoD4xelOURBP -----END ENCRYPTED PRIVATE KEY-----''' ), ) rsaPublicKeyPEM = '''-----BEGIN PUBLIC KEY----- MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL8eJ5AKoIsjURpcEoGubZMxLD7+kT+T Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQ== -----END PUBLIC KEY-----''' # Obtained using 'ssh-keygen -i -m PKCS8 -f rsaPublicKeyPEM' rsaPublicKeyOpenSSH = b('''ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAQQC/HieQCqCLI1EaXBKBrm2TMSw+/pE/ky6+1JLxLRa0YQwyjLbiCKtfRay+KVCDMpjzEiwZ94SS3t9A8OPBkDOF comment\n''') # The private key, in PKCS#1 format encoded with DER rsaKeyDER = a2b_hex( '''3082013b020100024100bf1e27900aa08b23511a5c1281ae6d93312c3efe 913f932ebed492f12d16b4610c328cb6e208ab5f45acbe2950833298f312 2c19f78492dedf40f0e3c190338502030100010240094483129f114dedf6 7edabc2301bc5a88e5e6601dd7016220ead9fd4bfc6fdeb75893898ae41c 54ddbdbf1539f8ccbd18f67b440de1ac30440281d40cfac839022100f20f 2f3e1da61883f62980922bd8df545ce407c726241103b5e2c53723124a23 022100ca1fe924792cfcc96bfab74f344a68b418df578338064806000fe2 a5c99a023702210087be1c3029504bcf34ec713d877947447813288975ca 240080af7b094091b12102206ab469fa6d5648a57531c8b031a4ce9db53b c3116cf433f5a6f6bbea5601ce05022100bd9f40a764227a21962a4add07 e4defe43ed91a3ae27bb057f39241f33ab01c1 '''.replace(" ","")) # The private key, in unencrypted PKCS#8 format encoded with DER rsaKeyDER8 = a2b_hex( '''30820155020100300d06092a864886f70d01010105000482013f3082013 b020100024100bf1e27900aa08b23511a5c1281ae6d93312c3efe913f932 ebed492f12d16b4610c328cb6e208ab5f45acbe2950833298f3122c19f78 492dedf40f0e3c190338502030100010240094483129f114dedf67edabc2 301bc5a88e5e6601dd7016220ead9fd4bfc6fdeb75893898ae41c54ddbdb f1539f8ccbd18f67b440de1ac30440281d40cfac839022100f20f2f3e1da 61883f62980922bd8df545ce407c726241103b5e2c53723124a23022100c a1fe924792cfcc96bfab74f344a68b418df578338064806000fe2a5c99a0 23702210087be1c3029504bcf34ec713d877947447813288975ca240080a f7b094091b12102206ab469fa6d5648a57531c8b031a4ce9db53bc3116cf 433f5a6f6bbea5601ce05022100bd9f40a764227a21962a4add07e4defe4 3ed91a3ae27bb057f39241f33ab01c1 '''.replace(" ","")) rsaPublicKeyDER = a2b_hex( '''305c300d06092a864886f70d0101010500034b003048024100bf1e27900a a08b23511a5c1281ae6d93312c3efe913f932ebed492f12d16b4610c328c b6e208ab5f45acbe2950833298f3122c19f78492dedf40f0e3c190338502 03010001 '''.replace(" ","")) n = int('BF 1E 27 90 0A A0 8B 23 51 1A 5C 12 81 AE 6D 93 31 2C 3E FE 91 3F 93 2E BE D4 92 F1 2D 16 B4 61 0C 32 8C B6 E2 08 AB 5F 45 AC BE 29 50 83 32 98 F3 12 2C 19 F7 84 92 DE DF 40 F0 E3 C1 90 33 85'.replace(" ",""),16) e = 65537 d = int('09 44 83 12 9F 11 4D ED F6 7E DA BC 23 01 BC 5A 88 E5 E6 60 1D D7 01 62 20 EA D9 FD 4B FC 6F DE B7 58 93 89 8A E4 1C 54 DD BD BF 15 39 F8 CC BD 18 F6 7B 44 0D E1 AC 30 44 02 81 D4 0C FA C8 39'.replace(" ",""),16) p = int('00 F2 0F 2F 3E 1D A6 18 83 F6 29 80 92 2B D8 DF 54 5C E4 07 C7 26 24 11 03 B5 E2 C5 37 23 12 4A 23'.replace(" ",""),16) q = int('00 CA 1F E9 24 79 2C FC C9 6B FA B7 4F 34 4A 68 B4 18 DF 57 83 38 06 48 06 00 0F E2 A5 C9 9A 02 37'.replace(" ",""),16) # This is q^{-1} mod p). fastmath and slowmath use pInv (p^{-1} # mod q) instead! qInv = int('00 BD 9F 40 A7 64 22 7A 21 96 2A 4A DD 07 E4 DE FE 43 ED 91 A3 AE 27 BB 05 7F 39 24 1F 33 AB 01 C1'.replace(" ",""),16) pInv = inverse(p,q) def testImportKey1(self): """Verify import of RSAPrivateKey DER SEQUENCE""" key = RSA.importKey(self.rsaKeyDER) self.assertTrue(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q) def testImportKey2(self): """Verify import of SubjectPublicKeyInfo DER SEQUENCE""" key = RSA.importKey(self.rsaPublicKeyDER) self.assertFalse(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) def testImportKey3unicode(self): """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as unicode""" key = RSA.importKey(self.rsaKeyPEM) self.assertEqual(key.has_private(),True) # assert_ self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q) def testImportKey3bytes(self): """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as byte string""" key = RSA.importKey(b(self.rsaKeyPEM)) self.assertEqual(key.has_private(),True) # assert_ self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q) def testImportKey4unicode(self): """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as unicode""" key = RSA.importKey(self.rsaPublicKeyPEM) self.assertEqual(key.has_private(),False) # failIf self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) def testImportKey4bytes(self): """Verify import of SubjectPublicKeyInfo DER SEQUENCE, encoded with PEM as byte string""" key = RSA.importKey(b(self.rsaPublicKeyPEM)) self.assertEqual(key.has_private(),False) # failIf self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) def testImportKey5(self): """Verifies that the imported key is still a valid RSA pair""" key = RSA.importKey(self.rsaKeyPEM) idem = key._encrypt(key._decrypt(89)) self.assertEqual(idem, 89) def testImportKey6(self): """Verifies that the imported key is still a valid RSA pair""" key = RSA.importKey(self.rsaKeyDER) idem = key._encrypt(key._decrypt(65)) self.assertEqual(idem, 65) def testImportKey7(self): """Verify import of OpenSSH public key""" key = RSA.importKey(self.rsaPublicKeyOpenSSH) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) def testImportKey8(self): """Verify import of encrypted PrivateKeyInfo DER SEQUENCE""" for t in self.rsaKeyEncryptedPEM: key = RSA.importKey(t[1], t[0]) self.assertTrue(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q) def testImportKey9(self): """Verify import of unencrypted PrivateKeyInfo DER SEQUENCE""" key = RSA.importKey(self.rsaKeyDER8) self.assertTrue(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q) def testImportKey10(self): """Verify import of unencrypted PrivateKeyInfo DER SEQUENCE, encoded with PEM""" key = RSA.importKey(self.rsaKeyPEM8) self.assertTrue(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q) def testImportKey11(self): """Verify import of RSAPublicKey DER SEQUENCE""" der = asn1.DerSequence([17, 3]).encode() key = RSA.importKey(der) self.assertEqual(key.n, 17) self.assertEqual(key.e, 3) def testImportKey12(self): """Verify import of RSAPublicKey DER SEQUENCE, encoded with PEM""" der = asn1.DerSequence([17, 3]).encode() pem = der2pem(der) key = RSA.importKey(pem) self.assertEqual(key.n, 17) self.assertEqual(key.e, 3) def test_import_key_windows_cr_lf(self): pem_cr_lf = "\r\n".join(self.rsaKeyPEM.splitlines()) key = RSA.importKey(pem_cr_lf) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e) self.assertEqual(key.d, self.d) self.assertEqual(key.p, self.p) self.assertEqual(key.q, self.q) ### def testExportKey1(self): key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) derKey = key.exportKey("DER") self.assertEqual(derKey, self.rsaKeyDER) def testExportKey2(self): key = RSA.construct([self.n, self.e]) derKey = key.exportKey("DER") self.assertEqual(derKey, self.rsaPublicKeyDER) def testExportKey3(self): key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) pemKey = key.exportKey("PEM") self.assertEqual(pemKey, b(self.rsaKeyPEM)) def testExportKey4(self): key = RSA.construct([self.n, self.e]) pemKey = key.exportKey("PEM") self.assertEqual(pemKey, b(self.rsaPublicKeyPEM)) def testExportKey5(self): key = RSA.construct([self.n, self.e]) openssh_1 = key.exportKey("OpenSSH").split() openssh_2 = self.rsaPublicKeyOpenSSH.split() self.assertEqual(openssh_1[0], openssh_2[0]) self.assertEqual(openssh_1[1], openssh_2[1]) def testExportKey7(self): key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) derKey = key.exportKey("DER", pkcs=8) self.assertEqual(derKey, self.rsaKeyDER8) def testExportKey8(self): key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) pemKey = key.exportKey("PEM", pkcs=8) self.assertEqual(pemKey, b(self.rsaKeyPEM8)) def testExportKey9(self): key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) self.assertRaises(ValueError, key.exportKey, "invalid-format") def testExportKey10(self): # Export and re-import the encrypted key. It must match. # PEM envelope, PKCS#1, old PEM encryption key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) outkey = key.exportKey('PEM', 'test') self.assertTrue(tostr(outkey).find('4,ENCRYPTED')!=-1) self.assertTrue(tostr(outkey).find('BEGIN RSA PRIVATE KEY')!=-1) inkey = RSA.importKey(outkey, 'test') self.assertEqual(key.n, inkey.n) self.assertEqual(key.e, inkey.e) self.assertEqual(key.d, inkey.d) def testExportKey11(self): # Export and re-import the encrypted key. It must match. # PEM envelope, PKCS#1, old PEM encryption key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) outkey = key.exportKey('PEM', 'test', pkcs=1) self.assertTrue(tostr(outkey).find('4,ENCRYPTED')!=-1) self.assertTrue(tostr(outkey).find('BEGIN RSA PRIVATE KEY')!=-1) inkey = RSA.importKey(outkey, 'test') self.assertEqual(key.n, inkey.n) self.assertEqual(key.e, inkey.e) self.assertEqual(key.d, inkey.d) def testExportKey12(self): # Export and re-import the encrypted key. It must match. # PEM envelope, PKCS#8, old PEM encryption key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) outkey = key.exportKey('PEM', 'test', pkcs=8) self.assertTrue(tostr(outkey).find('4,ENCRYPTED')!=-1) self.assertTrue(tostr(outkey).find('BEGIN PRIVATE KEY')!=-1) inkey = RSA.importKey(outkey, 'test') self.assertEqual(key.n, inkey.n) self.assertEqual(key.e, inkey.e) self.assertEqual(key.d, inkey.d) def testExportKey13(self): # Export and re-import the encrypted key. It must match. # PEM envelope, PKCS#8, PKCS#8 encryption key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) outkey = key.exportKey('PEM', 'test', pkcs=8, protection='PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC') self.assertTrue(tostr(outkey).find('4,ENCRYPTED')==-1) self.assertTrue(tostr(outkey).find('BEGIN ENCRYPTED PRIVATE KEY')!=-1) inkey = RSA.importKey(outkey, 'test') self.assertEqual(key.n, inkey.n) self.assertEqual(key.e, inkey.e) self.assertEqual(key.d, inkey.d) def testExportKey14(self): # Export and re-import the encrypted key. It must match. # DER envelope, PKCS#8, PKCS#8 encryption key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) outkey = key.exportKey('DER', 'test', pkcs=8) inkey = RSA.importKey(outkey, 'test') self.assertEqual(key.n, inkey.n) self.assertEqual(key.e, inkey.e) self.assertEqual(key.d, inkey.d) def testExportKey15(self): # Verify that that error an condition is detected when trying to # use a password with DER encoding and PKCS#1. key = RSA.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) self.assertRaises(ValueError, key.exportKey, 'DER', 'test', 1) def test_import_key(self): """Verify that import_key is an alias to importKey""" key = RSA.import_key(self.rsaPublicKeyDER) self.assertFalse(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e)
#!/usr/bin/env python3 from Cryptodome.Util import number N = 0x665166804cd78e8197073f65f58bca14e019982245fcc7cad74535e948a4e0258b2e919bf3720968a00e5240c5e1d6b8831d8fec300d969fccec6cce11dde826d3fbe0837194f2dc64194c78379440671563c6c75267f0286d779e6d91d3e9037c642a860a894d8c45b7ed564d341501cedf260d3019234f2964ccc6c56b6de8a4f66667e9672a03f6c29d95100cdf5cb363d66f2131823a953621680300ab3a2eb51c12999b6d4249dde499055584925399f3a8c7a4a5a21f095878e80bbc772f785d2cbf70a87c6b854eb566e1e1beb7d4ac6eb46023b3dc7fdf34529a40f5fc5797f9c15c54ed4cb018c072168e9c30ca3602e00ea4047d2e5686c6eb37b9 e = 0x2c998e57bc651fe4807443dbb3e794711ca22b473d7792a64b7a326538dc528a17c79c72e425bf29937e47b2d6f6330ee5c13bfd8564b50e49132d47befd0ee2e85f4bfe2c9452d62ef838d487c099b3d7c80f14e362b3d97ca4774f1e4e851d38a4a834b077ded3d40cd20ddc45d57581beaa7b4d299da9dec8a1f361c808637238fa368e07c7d08f5654c7b2f8a90d47857e9b9c0a81a46769f6307d5a4442707afb017959d9a681fa1dc8d97565e55f02df34b04a3d0a0bf98b7798d7084db4b3f6696fa139f83ada3dc70d0b4c57bf49f530dec938096071f9c4498fdef9641dfbfe516c985b27d1748cc6ce1a4beb1381fb165a3d14f61032e0f76f095d c = 0x503d5dd3bf3d76918b868c0789c81b4a384184ddadef81142eabdcb78656632e54c9cb22ac2c41178607aa41adebdf89cd24ec1876365994f54f2b8fc492636b59382eb5094c46b5818cf8d9b42aed7e8051d7ca1537202d20ef945876e94f502e048ad71c7ad89200341f8071dc73c2cc1c7688494cad0110fca4854ee6a1ba999005a650062a5d55063693e8b018b08c4591946a3fc961dae2ba0c046f0848fbe5206d56767aae8812d55ee9decc1587cf5905887846cd3ecc6fc069e40d36b29ee48229c0c79eceab9a95b11d15421b8585a2576a63b9f09c56a4ca1729680410da237ac5b05850604e2af1f4ede9cf3928cbb3193a159e64482928b585ac p = 98444549679044409506244239144443867459824227934526036052949278261505813439015297459200379108752444235232667213138464076415095486907288282630595622287237215801470940146886371515679909322090871473412384894540642399950010296214525469622505798526072170187467562765920044646574445427364231529083610955760228212701 q = 131205304707717699800023219057082007986286045823683571663112014612188606710079038751853416273709729039622908861933527111469616900188875912430487264576215232569029320804579614330240773622645122871884209068761138439268551367198798009790636662892148063583135747945604771740458352899202428704645256790931460695949 phi = (q-1)*(p-1) # TODO # e is too big for Wiener's Attack # use Boneh's attack instead # https://sagi.io/2016/04/crypto-classics-wieners-rsa-attack/ d = number.inverse(e, phi) print(number.long_to_bytes(pow(c, d, N)))
def calc_d(self): d = inverse(self.e, (self.p - 1) * (self.q - 1)) return d
def make_private_key_pem(self): d = inverse(self.e, (self.p - 1) * (self.q - 1)) rsa = RSA.construct((self.n, self.e, d)) return rsa.exportKey()
21711308225346315542706844618441565741046498277716979943478360598053144971379956916575370343448988601905854572029635846626259487297950305231661109855854947494209135205589258643517961521594924368498672064293208230802441077390193682958095111922082677813175804775628884377724377647428385841831277059274172982280545237765559969228707506857561215268491024097063920337721783673060530181637161577401589126558556182546896783307370517275046522704047385786111489447064794210010802761708615907245523492585896286374996088089317826162798278528296206977900274431829829206103227171839270887476436899494428371323874689055690729986771, 2734411677251148030723138005716109733838866545375527602018255159319631026653190783670493107936401603981429171880504360560494771017246468702902647370954220312452541342858747590576273775107870450853533717116684326976263006435733382045807971890762018747729574021057430331778033982359184838159747331236538501849965329264774927607570410347019418407451937875684373454982306923178403161216817237890962651214718831954215200637651103907209347900857824722653217179548148145687181377220544864521808230122730967452981435355334932104265488075777638608041325256776275200067541533022527964743478554948792578057708522350812154888097 ) # (N, e) pairs from friends friend_keys = [ (21711308225346315542706844618441565741046498277716979943478360598053144971379956916575370343448988601905854572029635846626259487297950305231661109855854947494209135205589258643517961521594924368498672064293208230802441077390193682958095111922082677813175804775628884377724377647428385841831277059274172982280545237765559969228707506857561215268491024097063920337721783673060530181637161577401589126558556182546896783307370517275046522704047385786111489447064794210010802761708615907245523492585896286374996088089317826162798278528296206977900274431829829206103227171839270887476436899494428371323874689055690729986771, 106979), (21711308225346315542706844618441565741046498277716979943478360598053144971379956916575370343448988601905854572029635846626259487297950305231661109855854947494209135205589258643517961521594924368498672064293208230802441077390193682958095111922082677813175804775628884377724377647428385841831277059274172982280545237765559969228707506857561215268491024097063920337721783673060530181637161577401589126558556182546896783307370517275046522704047385786111489447064794210010802761708615907245523492585896286374996088089317826162798278528296206977900274431829829206103227171839270887476436899494428371323874689055690729986771, 108533), (21711308225346315542706844618441565741046498277716979943478360598053144971379956916575370343448988601905854572029635846626259487297950305231661109855854947494209135205589258643517961521594924368498672064293208230802441077390193682958095111922082677813175804775628884377724377647428385841831277059274172982280545237765559969228707506857561215268491024097063920337721783673060530181637161577401589126558556182546896783307370517275046522704047385786111489447064794210010802761708615907245523492585896286374996088089317826162798278528296206977900274431829829206103227171839270887476436899494428371323874689055690729986771, 69557), (21711308225346315542706844618441565741046498277716979943478360598053144971379956916575370343448988601905854572029635846626259487297950305231661109855854947494209135205589258643517961521594924368498672064293208230802441077390193682958095111922082677813175804775628884377724377647428385841831277059274172982280545237765559969228707506857561215268491024097063920337721783673060530181637161577401589126558556182546896783307370517275046522704047385786111489447064794210010802761708615907245523492585896286374996088089317826162798278528296206977900274431829829206103227171839270887476436899494428371323874689055690729986771, 97117), (21711308225346315542706844618441565741046498277716979943478360598053144971379956916575370343448988601905854572029635846626259487297950305231661109855854947494209135205589258643517961521594924368498672064293208230802441077390193682958095111922082677813175804775628884377724377647428385841831277059274172982280545237765559969228707506857561215268491024097063920337721783673060530181637161577401589126558556182546896783307370517275046522704047385786111489447064794210010802761708615907245523492585896286374996088089317826162798278528296206977900274431829829206103227171839270887476436899494428371323874689055690729986771, 103231) ] c = 20304610279578186738172766224224793119885071262464464448863461184092225736054747976985179673905441502689126216282897704508745403799054734121583968853999791604281615154100736259131453424385364324630229671185343778172807262640709301838274824603101692485662726226902121105591137437331463201881264245562214012160875177167442010952439360623396658974413900469093836794752270399520074596329058725874834082188697377597949405779039139194196065364426213208345461407030771089787529200057105746584493554722790592530472869581310117300343461207750821737840042745530876391793484035024644475535353227851321505537398888106855012746117 # factorization of N p = 134460556242811604004061671529264401215233974442536870999694816691450423689575549530215841622090861571494882591368883283016107051686642467260643894947947473532769025695530343815260424314855023688439603651834585971233941772580950216838838690315383700689885536546289584980534945897919914730948196240662991266027 q = 161469718942256895682124261315253003309512855995894840701317251772156087404025170146631429756064534716206164807382734456438092732743677793224010769460318383691408352089793973150914149255603969984103815563896440419666191368964699279209687091969164697704779792586727943470780308857107052647197945528236341228473 phi = (q - 1) * (p - 1) # reverse encryption process for key in friend_keys[::-1]: d = number.inverse(key[1], phi) c = pow(c, d, N) print(number.long_to_bytes(c))
def calculateAverage(self): self.genElgamalKeys() n = len(self.user_list) round1_m = [] for i in range(n): round1_m.append(self.user_list[i].average_round1_all(self.m)) sum_of_ratings, sum_of_flags = self.multiplyRatings(round1_m) ratings_A = [] flags_A = [] for sum in sum_of_ratings: ratings_A.append(sum[0]) for sum in sum_of_flags: flags_A.append(sum[0]) # Round 1 Done #print(ratings_A) #print(sum_of_ratings) # Round 2 round2_m = [] for i in range(n): round2_m.append(self.user_list[i].average_round2( ratings_A, flags_A)) sum_plain_ratings = [] sum_plain_flags = [] for i in range(self.m): sum_plain_flags.append(0) sum_plain_ratings.append(0) for i in range(self.m): base = 1 for j in range(n): base = base * round2_m[j][i][0] % self.p # multiply all A_1 s sum_plain_ratings[i] = (sum_of_ratings[i][1] * inverse( base, self.p)) % self.p # Divide by B_1 sum_plain_ratings[i] = self.boundedDiscreteLog( sum_plain_ratings[i]) base = 1 for j in range(n): base = base * round2_m[j][i][1] % self.p # multiply all A_2 s sum_plain_flags[i] = (sum_of_flags[i][1] * inverse( base, self.p)) % self.p # Divide by B_2 sum_plain_flags[i] = self.boundedDiscreteLog(sum_plain_flags[i]) average_result = [] for i in range(self.m): inter_result = 0 if (sum_plain_flags[i] == 0): inter_result = sum_plain_flags[i] * 1.0 else: inter_result = sum_plain_ratings[i] * 1.0 / sum_plain_flags[ i] # calculate the actual average #print("Rating i", sum_plain_ratings[i]) #print("flags i", sum_plain_flags[i]) #average_result.append(inter_result) open if not stored as a multiple of 2 average_result.append(inter_result / 2) self.avg_ratings = average_result # list of m averages