Path: blob/master/RSA-encryption/Attack-Retrieve-Modulus/extractmod.py
1402 views
from Crypto.Util.number import *123def extractmod_eknown(_encrypt, e, limit=4):4"""5Reference: https://crypto.stackexchange.com/questions/43583/deduce-modulus-n-from-public-exponent-and-encrypted-data67Function to extract the value of modulus, given value of public key exponent89:input parameters:10_encrypt : <type 'function'> : Function interacting with the server for encryption11e : <type 'int' or 'long'> : Public Key exponent12limit : <type 'int'> : number of values to be sent for encryption13"""14try:15assert limit <= 416except AssertionError:17print "[+] Limit too big!"18return -119try:20m_list = [2, 3, 5, 7]21mod_list = [(bytes_to_long(_encrypt(long_to_bytes(m_list[i])))) - (m_list[i]**e) for i in range(limit)]22_GCD = mod_list[0]23for i in range(limit):24_GCD = GCD(_GCD, mod_list[i])25return _GCD26except Exception as ex:27print "[+] Exception: ", ex2829def extractmod_eunknown(_encrypt, limit=4):30"""31Reference: https://crypto.stackexchange.com/questions/43583/deduce-modulus-n-from-public-exponent-and-encrypted-data3233Function to extract the value of modulus without the value of public key exponent3435:input parameters:36_encrypt : <type 'function'> : Function interacting with the server for encryption37limit : <type 'int'> : number of values to be sent for encryption38"""39try:40assert limit <= 441except AssertionError:42print "[+] Limit too big!"43return -144try:45m_list = [2, 3, 5, 7]46ct_list = [bytes_to_long(_encrypt(long_to_bytes(m_list[i]**2))) for i in range(limit)]47ct_list2 = [bytes_to_long(_encrypt(long_to_bytes(m_list[i]))) for i in range(limit)]48assert len(ct_list) == len(ct_list2)49mod_list = [(ct_list2[i]**2 - ct_list[i]) for i in range(limit)]50_gcd = mod_list[0]51for i in mod_list:52_gcd = GCD(_gcd, i)53return _gcd54except Exception as ex:55print "[+] Exception: ", ex56return -1575859