def generateKeys(nbits=1024): ''' Generates a key pair public = (e,n) private = d such that n is nbits long (e,n) is vulnerable to the Wiener Continued Fraction Attack ''' # nbits >= 1024 is recommended assert nbits%4==0 p,q = getPrimePair(nbits//2) n = p*q phi = Arithmetic.totient(p, q) # generate a d such that: # (d,n) = 1 # 36d^4 < n good_d = False while not good_d: d = random.getrandbits(nbits//4) if (Arithmetic.gcd(d,phi) == 1 and 36*pow(d,4) < n): good_d = True e = Arithmetic.modInverse(d,phi) return e,n,d
def generateKeys(nbits=1024): ''' Generates a key pair public = (e,n) private = d such that n is nbits long (e,n) is vulnerable to the Wiener Continued Fraction Attack ''' # nbits >= 1024 is recommended assert nbits%4==0 p,q = getPrimePair(nbits//2) n = p*q phi = Arithmetic.totient(p, q) # generate a d such that: # (d,n) = 1 # 36d^4 < n good_d = False while not good_d: d = random.getrandbits(nbits//4) #if (Arithmetic.gcd(d,phi) == 1 and 36*pow(d,4) < n): if (Arithmetic.gcd(d,phi) == 1): good_d = True e = Arithmetic.modInverse(d,phi) return e,n,d
def evalStr(string): x = string[0] y = string[2] if isFloat(x): x = float(x) else: x = int(x) if isFloat(y): y = float(y) else: y = int(y) if (string[1] == "+"): from java.lang import Math import Arithmetic return Arithmetic.add(x, y) if (string[1] == "*"): from java.lang import Math import Arithmetic return Arithmetic.mult(x, y) if (string[1] == "-"): from java.lang import Math import Arithmetic return Arithmetic.subract(x, y) if (string[1] == "/"): from java.lang import Math import Arithmetic return Arithmetic.div(x, y)
def reconstruct(points, p): tmp_points = [ np.array([ arithm.ZPIfield(P[0][0], P[0][1], p), arithm.ZPIfield(P[1][0], P[1][1], p) ]) for P in points ] return np.array(tmp_points)
def squares(items): temp = "" for i in items: temp += str(i) temp += "," print "The squares of " + str(tuple(items)) + " are:" import Arithmetic Arithmetic.squares(temp) print""
def main(): print("operations on two numbers") print("enter the first number") a=int(input()) print("enter the second number") b=int(input()) print("addition is ",Arithmetic.Add(a,b)) print("subtraction is ",Arithmetic.Sub(a,b)) print("multiplication is ",Arithmetic.Mult(a,b)) print("Division is",Arithmetic.Div(a,b)) print("I did the changes")
def main(): no1 = int(input("Enter First Number :")) no2 = int(input("Enter Second Number :")) print("Calling Addition") print("Addition of {} and {} is {}".format(no1, no2, a.Add(no1, no2))) print("Calling Sub") print("Sub of {} and {} is {}".format(no1, no2, a.Sub(no1, no2))) print("Calling Div") print("Division of {} and {} is {}".format(no1, no2, a.Div(no1, no2))) print("Calling Mult") print("Mult of {} and {} is {}".format(no1, no2, a.Mult(no1, no2)))
def main(): print("enter the first number") no1=int(input()) print("Enter the second number") no2=int(input()) Arithmetic.Add(no1,no2) Arithmetic.Sub(no1,no2) Arithmetic.Mult(no1,no2) Arithmetic.Div(no1,no2)
def main(): no1 = int(input("enter the no1=")) no2 = int(input("enter the no2=")) ans = Arithmetic.Add(no1, no2) print("\n Addition is=", ans) ans = Arithmetic.Sub(no1, no2) print("\nSubstraction is=", ans) ans = Arithmetic.Mult(no1, no2) print("\nMultiplicaton is= ", ans) ans = Arithmetic.Div(no1, no2) print("\n Division is=", ans)
def CRT_RSA(d, p, q, entier): n = p * q _p = n / p _q = n / q x1 = crt_pow(entier,d,p) x2 = crt_pow(entier,d,q) part1 = x1 * _p * Arithmetic.modInverse(_p, p) part2 = x2 * _q * Arithmetic.modInverse(_q, q) return int((part1+part2) % n)
def main(): iNo1 = int(input("Enter number 1 : ")) iNo2 = int(input("Enter number 2 : ")) print("Addition of {} and {} is {}".format(iNo1, iNo2, Arithmetic.Add(iNo1, iNo2))) print("Subtraction of {} and {} is {}".format(iNo1, iNo2, Arithmetic.Sub(iNo1, iNo2))) print("Multiplication of {} and {} is {}".format( iNo1, iNo2, Arithmetic.Mult(iNo1, iNo2))) print("Division of {} and {} is {}".format(iNo1, iNo2, Arithmetic.Div(iNo1, iNo2)))
def hack_RSA(e, n): ''' Finds d knowing (e,n) applying the Wiener continued fraction attack ''' # n = input("Enter e number: ") # e = input("Enter n number: ") frac = ContinuedFractions.rational_to_contfrac(e, n) convergents = ContinuedFractions.convergents_from_contfrac(frac) for (k, d) in convergents: #check if d is actually the key if k != 0 and (e * d - 1) % k == 0: phi = (e * d + 1) // k s = n - phi + 1 # check if the equation x^2 - s*x + n = 0 # has integer roots discr = s * s - 4 * n if (discr >= 0): t = Arithmetic.is_perfect_square(discr) if t != -1 and (s + t) % 2 == 0: print("Hacked!") print("-------------------------") print("d = ", d) print("-------------------------")
def substract(self, a, b, current=None): if a < 0 or b < 0 or b > a: ex = Arithmetic.GenericError() ex.reason = "non natural argument or result" raise ex else: return a - b
def hack_RSA(e, n): ''' Finds d knowing (e,n) applying the Wiener continued fraction attack ''' frac = ContinuedFractions.rational_to_contfrac( e, n) # Создаём list частных непрерывных дрообей [a0, ..., an] convergents = ContinuedFractions.convergents_from_contfrac( frac) # вычисление подходящих дробей for (k, d) in convergents: # print('k, d: ', k, d) #check if d is actually the key if k != 0 and (e * d - 1) % k == 0: phi = (e * d - 1) // k s = n - phi + 1 # check if the equation x^2 - s*x + n = 0 # has integer roots discr = s * s - 4 * n # print(phi, s, discr) if (discr >= 0): t = Arithmetic.is_perfect_square(discr) # print('sqrt: ', t) if t != -1 and (s + t) % 2 == 0: print("Hacked!") return d
def generate_keypair(p, q): if not (Arithmetic.premier(p) and Arithmetic.premier(q)): raise ValueError('Les deux nombres doivent être premiers!') elif p == q: raise ValueError('p et q ne peuvent pas être égaux!') n = p * q phi = (p - 1) * (q - 1) good_d = False while not good_d: d = random.getrandbits(4) if Arithmetic.gcd(d, phi) == 1 and 3 * pow(d, 4) < n: good_d = True e = Arithmetic.modInverse(d, phi) return e, n, d
def main(): print("Enter first number : ") value1 = int(input()) print("Enter second number : ") value2 = int(input()) ret1 = Arithmetic.Addition(value1, value2) ret2 = Arithmetic.Substraction(value1, value2) ret3 = Arithmetic.Multiplication(value1, value2) ret4 = Arithmetic.Division(value1, value2) print("Addition is :", ret1) print("Substraction is : ", ret2) print("Multiplication is : ", ret3) print("Division is : ", ret4)
def generateKeys(nbits): assert nbits % 4 == 0 p, q = getPrimePair(nbits // 2) print("p=", p) print("q=", q) n = p * q phi = Arithmetic.totient(p, q) good_d = False while not good_d: d = random.getrandbits(nbits // 4) if (Arithmetic.gcd(d, phi) == 1 and 3 * pow(d, 4) < n): good_d = True e = Arithmetic.modInverse(d, phi) return e, n, d
def generateKeys(nbits=1024): p = getPrime(512) q = getPrime(512) print("primes:", p, q) n = p * q # phi=EulerPhi(n) phi = (p - 1) * (q - 1) # public=(e,n) # private= d, тчо НОД(d,n)=1 good_d = False while not good_d: d = random.getrandbits(nbits // 4) if Arithmetic.gcd(d, phi) == 1: good_d = True # подразумеваем, что умеем находить обратный элемент по модулю e = Arithmetic.modInverse(d, phi) return e, n, d
def InvokeArth(iNum1, iNum2): print("Arithmatic Operations\n") # Make addition iRet = arithm.Add(iNum1,iNum2) print("Addition of {} and {} is =>\t\t{}".format(iNum1,iNum2,iRet)) # Make addition iRet = arithm.Sub(iNum1,iNum2) print("Substraction of {} and {} is =>\t\t{}".format(iNum1,iNum2,iRet)) # Make addition iRet = arithm.Mult(iNum1,iNum2) print("Multiplication of {} and {} is =>\t{}".format(iNum1,iNum2,iRet)) # Make addition iRet = arithm.Div(iNum1,iNum2) print("Division of {} and {} is =>\t\t{}".format(iNum1,iNum2,iRet))
def RSA_fast_dec(ct, pri_key): ''' RSA fast decryption(by a factor of 4) :param int ct: integer representation of ciphertext :param dict pri_key: private key {'d':xx, 'n':xx, 'p':xx, 'q':xx} :return: plaintext after decryption :rtype: int ''' n, d, p, q = pri_key['n'], pri_key['d'], pri_key['p'], pri_key['q'] xp = ct % p xq = ct % q dp = d % (p - 1) dq = d % (q - 1) yp = pow(xp, dp, p) yq = pow(xq, dq, q) cp = Arithmetic.modInverse(q, p) cq = Arithmetic.modInverse(p, q) return (q * cp * yp + p * cq * yq) % n
def main(): no1 = int(input("Enter first no :")) no2 = int(input("Enter second no :")) ret = Addition(no1, no2) print("Addition is:", ret) print("Addition of {} and {} is {}".format(no1, no2, ret)) ret = Arithmetic.Substraction(no1, no2) print("Substraction of {} and {} is {}".format(no1, no2, ret))
def CRTmethod(e, n, entier): N = 1 for element in n: N *= element _n = [int((N / element)) for element in n] modinv = [Arithmetic.modInverse(_n[i], n[i]) for i in range(0,e)] result = [(entier[i] * _n[i] * modinv[i]) for i in range(0,e)] summod = sum(result) % N msg = round(pow(summod, 1/e)) return msg
def wiener(e, n): time.sleep(1) frac = ContinuedFractions.rational_to_contfrac(e, n) convergents = ContinuedFractions.convergents_from_contfrac(frac) for (k, d) in convergents: if k != 0 and (e * d - 1) % k == 0: phi = (e * d - 1) // k s = n - phi + 1 discr = s * s - 4 * n if (discr >= 0): t = Arithmetic.is_perfect_square(discr) if t != -1 and (s + t) % 2 == 0: return d
def wiener(e,n): time.sleep(1) frac = ContinuedFractions.rational_to_contfrac(e, n) convergents = ContinuedFractions.convergents_from_contfrac(frac) for (k,d) in convergents: if k!=0 and (e*d-1)%k == 0: phi = (e*d-1)//k s = n - phi + 1 discr = s*s - 4*n if(discr>=0): t = Arithmetic.is_perfect_square(discr) if t!=-1 and (s+t)%2==0: return d
def wiener(e, n): frac = ContinuedFractions.rational_to_contfrac(e, n) convergents = ContinuedFractions.convergents_from_contfrac(frac) for (k,d) in convergents: if k!=0 and (e*d-1)%k == 0: phi = (e*d-1)//k s = n - phi + 1 # check if the equation x^2 - s*x + n = 0 # has integer roots discr = s*s - 4*n if(discr>=0): t = Arithmetic.is_perfect_square(discr) if t!=-1 and (s+t)%2==0: return d
def hack_RSA(e, n): print "Hacking" frac = ContinuedFractions.rational_to_contfrac(e, n) convergents = ContinuedFractions.convergents_from_contfrac(frac) for (k, d) in convergents: if k != 0 and (e * d - 1) % k == 0: phi = (e * d - 1) // k s = n - phi + 1 discr = s * s - 4 * n if (discr >= 0): t = Arithmetic.is_perfect_square(discr) if t != -1 and (s + t) % 2 == 0: print "done" print d return d
def RSA_keygen(bits): ''' RSA key generation :param int bits: bit length of the modulus n. :return: public key {'e':xx, 'n':xx} and private key {'d':xx, 'n':xx, 'p':xx, 'q':xx} :rtype: tuple of dicts ''' pub_key = {} pri_key = {} p = getprime(bits // 2) q = getprime(bits // 2) n = p * q phi = (p - 1) * (q - 1) while True: e = random.randint(1, phi - 1) if Arithmetic.gcd(e, phi) == 1: pub_key['e'] = e pub_key['n'] = n pri_key['p'] = p pri_key['q'] = q pri_key['d'] = Arithmetic.ModInverse(e, phi) pri_key['n'] = n return (pub_key, pri_key)
def RSA_keygen(n): ''' RSA key generation :param int n: bit length of prime p,q :return: public key {'e':xx, 'n':xx} and private key {'d':xx, 'n':xx, 'p':xx, 'q':xx} :rtype: tuple of dicts ''' pub_key = {} pri_key = {} p = getprime(n) q = getprime(n) n = p * q phi = (p - 1) * (q - 1) while 1: e = random.randint(1, phi - 1) if Arithmetic.gcd(e, phi) == 1: pub_key['e'] = e pub_key['n'] = n pri_key['p'] = p pri_key['q'] = q pri_key['d'] = Arithmetic.modInverse(e, n) pri_key['n'] = n return (pub_key, pri_key)
def wiener_hack(e, n): # https://github.com/pablocelayes/rsa-wiener-attack frac = ContinuedFractions.rational_to_contfrac(e, n) convergents = ContinuedFractions.convergents_from_contfrac(frac) for (k, d) in convergents: if k != 0 and (e * d - 1) % k == 0: phi = (e * d - 1) // k s = n - phi + 1 discr = s * s - 4 * n if (discr >= 0): t = Arithmetic.is_perfect_square(discr) if t != -1 and (s + t) % 2 == 0: print("Hacked!") return d return False
def hack_RSA(e, n): print "Hacking" frac = ContinuedFractions.rational_to_contfrac(e, n) convergents = ContinuedFractions.convergents_from_contfrac(frac) for (k, d) in convergents: if k != 0 and (e * d - 1) % k == 0: phi = (e * d - 1) // k s = n - phi + 1 discr = s * s - 4 * n if(discr >= 0): t = Arithmetic.is_perfect_square(discr) if t != -1 and (s + t) % 2 == 0: print "done" print d return d
def evaluate(line, mode): global _do_block global _looking_for_end_bracket global _record_lines global _lines global _same_string if line == "quit": return 1 sline = line.split(" ") sline = _convert_to_values(1, sline) sline = Arithmetic.do_arithmetic_statements(sline) sline = IfElse.do_boolean_expressions(sline) sline = _booleans_to_ints(sline) # Checking if the line is both from a file and an if statement if mode: if _is_if_statement_true(sline) or _is_else_if_statement_true(sline, _same_string) or _is_else_statement_true(sline, _same_string): _do_block = True _same_string = True elif _is_start_bracket(sline): _record_lines = True _looking_for_end_bracket = True elif _looking_for_end_bracket and _is_end_bracket(sline): _record_lines = False _looking_for_end_bracket = False if _do_block: IfElse.perform_block_statement(_lines, mode) _lines = [] _do_block = False elif _record_lines: _lines.append(line) return 0 elif _is_else_if_statement(sline) or _is_else_statement(sline) or _do_block: pass else: _same_string = False # Checking if the line is a variable set statement if _is_variable_set_statement(sline): val = Variable.variable_set_statement(sline) if val: return val # Checking if the line is a print statement if _is_print_statement(sline): val = Print.print_statement(sline) if val: return val return 0
def hack_RSA(e,n): print "[+] Wiener attack in progress..." frac = ContinuedFractions.rational_to_contfrac(e, n) convergents = ContinuedFractions.convergents_from_contfrac(frac) for (k,d) in convergents: #check if d is actually the key if k!=0 and (e*d-1)%k == 0: phi = (e*d-1)//k s = n - phi + 1 # check if the equation x^2 - s*x + n = 0 # has integer roots discr = s*s - 4*n if(discr>=0): t = Arithmetic.is_perfect_square(discr) if t!=-1 and (s+t)%2==0: return d
def hack_RSA(e, n): frac = ContinuedFractions.rational_to_contfrac(e, n) convergents = ContinuedFractions.convergents_from_contfrac(frac) for (k, d) in convergents: #check if d is actually the key if k != 0 and (e * d - 1) % k == 0: phi = (e * d - 1) // k s = n - phi + 1 # check if the equation x^2 - s*x + n = 0 discr = s * s - 4 * n if (discr >= 0): t = Arithmetic.is_perfect_square(discr) if t != -1 and (s + t) % 2 == 0: print("Xong!") return d
def hack_RSA(e, n): frac = FractionsContinues.rational_to_contfrac(e, n) convergents = FractionsContinues.convergents_from_contfrac(frac) for (k, d) in convergents: if k != 0 and (e * d - 1) % k == 0: phi = (e * d - 1) // k s = n - phi + 1 discr = s * s - 4 * n if discr >= 0: t = Arithmetic.is_perfect_square(discr) if t != -1 and (s + t) % 2 == 0: print("Hacked!") return d else: print("nope")
def hack_RSA(e, n): """ Finds d knowing (e, n) applying the Wiener continued fraction attack """ frac = ContinuedFractions.rational_to_contfrac(e, n) convergents = ContinuedFractions.convergents_from_contfrac(frac) for (k, d) in convergents: # Check if d is actually the key if k != 0 and (e * d - 1) % k == 0: phi = (e * d - 1) // k s = n - phi + 1 # Check if the equation x^2 - s*x + n = 0 has integer roots discr = s * s - 4 * n if(discr >= 0): t = Arithmetic.is_perfect_square(discr) if t != -1 and (s + t) % 2 == 0: return d return None
def handleLine(self, line, fileName="", index=0): """This function sends a line to translation to assembly based on if its a pop, push or arithmetic command""" lineEdit = line.replace("\n", "").rstrip() lineSplit = lineEdit.split(" ") if len(lineSplit) == 3: if lineSplit[0] == "function": lineObject = FD.FunctionDecl(lineSplit[1], lineSplit[2]) self.funcName = lineSplit[1] + "$" elif lineSplit[0] == "call": lineObject = FC.FunctionCall(index, self.funcName, lineSplit[1], lineSplit[2]) else: lineObject = S.Segment(line, lineSplit[0], lineSplit[1], lineSplit[2], fileName) elif self.isArithmetic(line): # Arithmetic lineObject = A.Arithmetic(line, lineSplit[0], index, self.funcName) elif ("goto" in line) or ("label" in line): lineObject = C.Conditionals(line, self.funcName) elif "return" in line: lineObject = FD.FunctionDecl() return "//" + line + "\n" + lineObject.writeLine()
import Validator as Validator if __name__ == "__main__": print( "Type \"quit\" to stop program\nType \"details 0/1\" to stop show or not show parser details.\n" ) showdetails = False txt = input(">> ") while (txt != "quit"): if txt.startswith("details") and len(txt.split()) == 2: if txt.split()[1] == "1": showdetails = True if txt.split()[1] == "0": showdetails = False else: if Validator.validate(txt): expression = Parser.parse(txt) result = Arithmetic.calculate(expression) if showdetails: tokens = Parser.tokenize(txt) tokenstring = "tokens: " for t in tokens: tokenstring += str(t) print(tokenstring) print("Parser:", expression) print("Arithmetic:", result) else: print(result) txt = input(">> ")
def _has_arithmetic_statement(sline): return Arithmetic.has_arithmetic_statement(sline) #### # If/Else # def _is_start_bracket(sline): return len(sline) == 1 and sline[0] == "{"
''' for i in range(5): e,n,d = generateKeys() print ("Clave Publica:") print("e =") print(e) print("n =") print(n) print ("Clave Privada:") print("d =") print(d) print("-----------------------") ''' for i in range(10): e,n,d = generateKeys() sqrtn = Arithmetic.isqrt(n) n1 = int(sqrtn*1.5) n2 = int(sqrtn*2.5) with open('../data/'+str(i)+'.data','w') as f: f.write('[\n') f.write('[1 0 '+str(e)+' '+str(e)+']\n') f.write('[0 1 '+str(n-random.randrange(n1,n2))+' '+str(n-random.randrange(n1,n2))+']\n') f.write('[0 0 0 0]\n') f.write('[0 0 0 0]\n') f.write(']') with open('../data/'+str(i)+'.result','w') as f1: f1.write(str(d)) print('end\n')