Exemple #1
0
import socket
import random as r
import sympy as sy


def create_gen(prime):
    return (r.randrange(2, prime - 2))


prime = sy.randprime(2, 500000)
print("The Prime Number is=" + str(prime))
gen = create_gen(prime)
print("The Generator is=" + str(gen))

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12345
s.connect(("127.0.0.1", port))

while True:
    y = str(r.randrange(0, prime))

    prime = str(prime) + ","
    prime = prime.encode()
    s.send(prime)
    gen = str(gen).encode()
    s.send(gen)

    R1 = s.recv(1024).decode()
    print("Y=" + y)
    print("R1=" + R1)
    R1 = int(R1)
import sympy
import random

p = sympy.randprime(40000, 50000)

while p % 4 != 3:
    p = sympy.nextprime(p)  #generating the first prime number

q = sympy.randprime(40000, 50000)

while q % 4 != 3 and q != p:
    q = sympy.nextprime(q)  #generating the second prime number

M = p * q  #calculating the M parameter

s = random.randrange(M)  #generating random seed smaller then M
print('p: ' + str(p) + ' q: ' + str(q) + ' M: ' + str(M) + ' S: ' + str(s))
tab = []
outtab = []
outdec = 0
seqdec = []
size = 320
x0 = (s * s) % M

count = 0
while (count !=
       size):  #generating given quantity of numbers via the BBS algorithm
    x = (x0 * x0) % M
    tab.append(
        x0
        & 1)  #extracting the least significant bit form the generated number
Exemple #3
0
def generateKey():
    return sympy.randprime(200, 20000), sympy.randprime(200, 20000)
def serve():
    """
    The server code. Accepts connections from clients and transfers a file.
    The file should be in the same directory. Ensure that there is only 
    one client connecting. This is not multi-threaded at this point.
    """
    print('Server listening....')
    while True:
        conn, addr = s.accept(
        )  # Establish connection with client, returns a tuple
        print('Got connection from', addr)
        data = conn.recv(1024)  # Receive from server
        print('Server received', repr(data))

        # Agree on shared prime 'p' and shared key 'g'
        p = sympy.randprime(200, 9999)  # random prime generator for 'p'
        # restricted prime from 200 to 9999 for time & computation sake

        print('p = ', p)  # print out prime

        gList = list(_primitive_root_prime_iter(
            p))  # generate array of possible g values
        # that satisfy g^(p-1) = 1 (mod p)
        # print(gList)  # Debugging!
        randomG = random.SystemRandom()
        g = randomG.choice(
            gList)  # get random primitive root modulo from array
        print('g = ', g)

        conn.sendall(p.to_bytes(16,
                                'big'))  # send 'p' as bytes, 16 B, big endian
        conn.sendall(g.to_bytes(16, 'big'))  # send 'g' to client

        # Generate secret prime 'p2'
        p2 = sympy.randprime(2, 2000)  # random prime 'p2'
        while p2 == p:  # p2 != p
            p2 = sympy.randprime(2, 2000)  # random 'p2' prime (secret)

        print('p2 = ', p2)  # debugging p2 (only server knows)

        # Generate public key Pk2 = g^(p2) mod p
        Pk2 = pow(g, p2,
                  p)  #pow(x,y[,z]) computers g^(y)mod(z) more efficiently
        print('Pk2 = ', Pk2)

        # Receive Pk1 from Client (1)
        Pk1 = conn.recv(1024)
        Pk1 = int.from_bytes(Pk1, byteorder='big')  # convert Pk1 bytes -> int
        print('Pk1 = ', Pk1)

        # Send Pk2 to Client (2)
        conn.sendall(Pk2.to_bytes(16, 'big'))

        # Get Client Shared Key (3)
        Pk1_p2 = pow(Pk1, p2)
        Pk1_p2 = Pk1_p2 % p  # Pk1_p2 = Pk1^p2 % p
        print('\nShared DH key: ', Pk1_p2)  # should match with client's Pk2_p1

        # file to transfer
        filename = 'sample.txt'
        f = open(filename, 'r')  #formerly rb from template (read all at once)
        l = f.read()  # extract contents of file
        l = l.rjust(32)  # right justified, width of string
        l = str.encode(l)  # l as a string to bytes
        print('read: ', l)

        # debugging
        #l = b'Hi there'.rjust(32)

        # Encrypt file
        Pk1_p2 = Pk1_p2.to_bytes(16, 'big')  # convert shared key to bytes
        print(Pk1_p2)
        # AES encryption with key
        cipher = AES.new(Pk1_p2, AES.MODE_ECB)  # create new AES cipher
        ciphertext = base64.b64encode(
            cipher.encrypt(l))  # encrypt 'l' file text
        print('\nCiphertext: ', ciphertext)

        # Send encrypted file
        conn.sendall(ciphertext)  #send -> sendall b/c Python3
        print('\nSent ', repr(ciphertext))  # print ciphertext sent to client

        # Client acknowledges transfer completed
        thankyou = conn.recv(1024)
        print(thankyou)

        # Implement MD5 hash on Ciphertext
        md5hash = hashlib.md5(ciphertext).hexdigest()
        print('\nMD5 Hash: ', md5hash)
        conn.sendall(str.encode(md5hash))  # send md5hash for comparison

        f.close()  # close input file
        print('Done sending')
        #conn.send(b'File transfer complete!')
        conn.close()  # close socket connection
def gener_key():
    p = sympy.randprime(pow(2, 10), pow(2, 20))
    q = random.randint(1, p - 1)
    x = random.randint(2, p - 2)
    y = pow(q, x, p)
    return p, q, y
Exemple #6
0
def GenModulus(w):
    n = len(w) // 2
    p = randprime(2**n, 2**(n + 1))
    q = randprime(2**n, 2**(n + 1))
    N = p * q
    return N, p, q
Exemple #7
0
#!/usr/bin/env python3
import sympy
import json

m = sympy.randprime(2**257, 2**258)
M = sympy.randprime(2**257, 2**258)
a, b, c = [(sympy.randprime(2**256, 2**257) % m) for _ in range(3)]

x = (a + b * 3) % m
y = (b - c * 5) % m
z = (a + c * 8) % m

flag = int(open('flag', 'rb').read().strip().hex(), 16)
p = pow(flag, a, M)
q = pow(flag, b, M)

json.dump({key: globals()[key] for key in "Mmxyzpq"}, open('crypted', 'w'))
Exemple #8
0
 def gen_x(r):
     return randprime(1, r)  # Maybe x should be big?
 def __init__(self, public_key1, public_key2):
     self.public_key1 = public_key1
     self.public_key2 = public_key2
     self.private_key = sympy.randprime(100, 1000)
     self.full_key = None
Exemple #10
0
    def dnl(self, resolution=0.01, method='fast'):
        """
        calculate the differential non linearity.
        :param resolution: represents the ratio between the error of DNL and ideal LSB.
        :param method: 'fast': fast algorithm, which computes the transition levels directly
                       'iterative': find the transition levels iteratively
                       'code_density': based on the code density theory.
        :return: a list of DNLs.
        """
        if method == 'iterative':
            lsb_ideal = self.vref / (2**self.n)
            step = lsb_ideal * resolution
            ramp = np.arange(0, self.vref, step)

            # digital_output = np.asarray([self.sar_adc(x)[-1] for x in ramp])
            # digital_output = np.asarray([list(x) for x in digital_output], dtype=np.int64)
            # exp_array = np.asarray([2**(self.n-1-i) for i in range(self.n)])
            # digital_output_decimal = np.inner(exp_array, digital_output)

            # if resolution < 0.01, a huge amount of calculation is required,
            # so use for loop to calculate for the sub-array, in order to avoid stackoverflow
            # by calling fast_conversion method directly
            if resolution < 0.01:
                digital_output_decimal = np.array([])
                for i in range(2**self.n):
                    temp = fast_conversion(
                        ramp[int(i / resolution):int((i + 1) / resolution)],
                        weights=self.weights,
                        n=self.n,
                        vref=self.vref)
                    digital_output_decimal = np.concatenate(
                        (digital_output_decimal, temp))
            else:
                digital_output_decimal = fast_conversion(ramp,
                                                         weights=self.weights,
                                                         n=self.n,
                                                         vref=self.vref)

            tran_lvls = np.array([], dtype=np.int64)
            miss_code_count = 0
            dnl = []
            for i in range(2**self.n):
                position_array = np.where(
                    digital_output_decimal ==
                    i)  # the 'where' method returns a tuple
                if position_array[0].size != 0:
                    tran_lvls = np.append(tran_lvls, position_array[0][0])
                else:
                    miss_code_count += 1
            print('number of misscode:', miss_code_count)
            for i in range(len(tran_lvls) - 1):
                dnl += [(tran_lvls[i + 1] - tran_lvls[i]) * resolution - 1]
            return dnl
        elif method == 'fast':
            decision_lvls = get_decision_lvls(self.weights, self.n, self.vref)
            ideal_lsb = self.vref / (2**self.n)
            dnl = np.diff(decision_lvls) / ideal_lsb - 1
            return dnl

        elif method == 'code_density':
            sine_amp = self.vref / 2
            fs = 5e6
            Ts = 1 / fs
            n_record = np.pi * (2**(self.n - 1)) * (1.96**2) / (resolution**2)
            print('number of records: %s' % ('{:e}'.format(n_record)))
            t = np.arange(0, n_record * Ts, Ts)
            fin = randprime(0, 0.5 * n_record) / n_record * fs
            sine_wave = sine_amp * np.sin(2 * np.pi * fin * t) + self.vcm

            # digital_output = [self.sar_adc(x)[-1] for x in sine_wave]
            # bi2deDict = getbi2deDict(self.n)
            # digital_output_decimal = [bi2deDict[x] for x in digital_output]
            digital_output_decimal = fast_conversion(sine_wave,
                                                     weights=self.weights,
                                                     n=self.n,
                                                     vref=self.vref)
            min_hit_num = np.amin(digital_output_decimal)
            max_hit_num = np.amax(digital_output_decimal)
            code_hist, bins = np.histogram(
                digital_output_decimal, np.arange(min_hit_num,
                                                  max_hit_num + 1))
            ''''
            plt.hist(digital_output_decimal, np.arange(2 ** self.n))
            print('max(codHist)', np.argmax(code_hist),np.amax(code_hist))
            plt.axis([0,2**self.n, np.amin(code_hist), np.max(code_hist)])
            '''

            code_cum_hist = np.cumsum(code_hist)
            tran_lvl = -np.cos(np.pi * code_cum_hist / sum(code_hist))
            code_hist_lin = np.array(tran_lvl[1:]) - np.array(tran_lvl[:-1])
            trunc = 1
            code_hist_trunc = code_hist_lin[trunc:-trunc]
            actual_lsb = sum(code_hist_trunc) / (len(code_hist_trunc))
            dnl = np.concatenate(([0], code_hist_trunc / actual_lsb - 1))
            return dnl
Exemple #11
0
import json
from sympy import randprime

p = randprime(2 ** 512, 2 ** 513)
q = randprime(2 ** 512, 2 ** 513)
n = p * q

e1 = randprime(2 ** 1000, 2 ** 1001)
e2 = randprime(2 ** 1000, 2 ** 1001)

m = int(open('flag').read().strip().encode('hex'), 16)
assert m < n
c1 = pow(m, e1, n)
c2 = pow(m, e2, n)

print json.dumps({'n': n, 'e1': e1, 'e2': e2, 'c1': c1, 'c2': c2})

Exemple #12
0
 def randomPrime(self, range):
     self.primeN = sympy.randprime(0, self.prange)
     return self.primeN
Exemple #13
0
def _getNPQ(bits):
    p = randprime(2**((bits // 2) - 1), 2**(bits // 2))
    q = randprime(2**((bits // 2) - 1), 2**(bits // 2))
    p, q = max(p, q), min(p, q)
    n = p * q
    return n, p, q
Exemple #14
0
import json
from sympy import randprime
p = randprime(2 ** 157, 2 ** 158)
q = randprime(2 ** 157, 2 ** 158)
n = p * q
e = 65537
m = int(open('flag').read().strip().encode('hex'), 16)
assert m < n
c = pow(m, e, n)
print json.dumps({'n': n, 'e': e, 'c': c})
from hashlib import sha256
import random
import sympy

print("Input n - your choice for length of prime")
n = int(input())
# sympy.randprime(a,b) gives us a random prime between and b
# So to get a random prime of length n, we use a as (10 power n-1) and (b as 10 power n )-1
x = sympy.randprime(pow(10, n - 1), pow(10, n) - 1)
print("The random prime is", x)


#this is using the inbuilt library for SHA hash function
def SHAHash(r, M):
    hash = sha256()
    hash.update(str(r).encode())
    hash.update(M.encode())
    return int(hash.hexdigest(), 16)


#this is using my own hash function as described in the solution to Q.
def dlpHash(r, M, g, y, q):
    mm = ''.join(
        format(i, 'b') for i in bytearray(M, encoding='utf-8')
    )  #this gives us the binary representation of the message string
    print("Binary representation of message is: ", mm)
    m_dec = int(mm, 2)  #Converting that binary to decimal
    print("Decimal representation of binary encoded message is: ", m_dec)
    print("\n")
    return ((pow(g, r) % q) * (pow(y, m_dec % q) % q)) % q
Exemple #16
0
import sympy

print('5 is a Prime Number',sympy.isprime(5))

print(list(sympy.primerange(0,100))


print(sympy.randprime(0,100)) #Output 83
print(sympy.randprime(0,100)) #Output 41
print(sympy.prime(3)) #Output 5
print(sympy.prevprime(50)) #Output 47
print(sympy.nextprime(50)) #Output 53
Exemple #17
0
    try:
        x = int(input("x = "))
        y = int(input("y = "))
        z = int(input("z = "))
    except ValueError:
        print("Invalid input!")
        exit()
    ans = x ** 3 + y ** 3 + z ** 3
    print(f"({x}) ^ 3 + ({y}) ^ 3 + ({z}) ^ 3 = {ans}")
    if ans == 42:
        print(open("flag1").read())
    else:
        print("Sorry, you are not Deep Thought.")
        exit()

    n = sympy.randprime(3, 2 ** 256) * sympy.randprime(3, 2 ** 256)
    print()
    print(
        "Since you already know the Answer to Everything, could you give me 8 integers, a, b, c, d, i, j, k and l, such that"
    )
    print(
        f"a^3 + b^3 + c^3 + d^3 = i^2 + j^2 + k^2 + l^2 = random_prime(2^256) * random_prime(2^256) = {n}"
    )
    print()
    try:
        a = int(input("a = "))
        b = int(input("b = "))
        c = int(input("c = "))
        d = int(input("d = "))
        i = int(input("i = "))
        j = int(input("j = "))
Exemple #18
0
def generate_public_keys(min_val, max_val):
    public_p = randprime(min_val, max_val)
    public_g = generate_public_g(public_p)
    return public_p, public_g
Exemple #19
0
from sympy import randprime
import random
from math import gcd

q = randprime(100, 1000)


# finds primitive roots of modulo
def primRoots(modulo):
    required_set = {num for num in range(1, modulo) if gcd(num, modulo)}
    return [
        g for g in range(1, modulo) if required_set ==
        {pow(g, powers, modulo)
         for powers in range(1, modulo)}
    ]


alpha = random.choice(primRoots(q))
X_A = random.randint(1, q - 1)
X_B = random.randint(1, q - 1)

Y_A = (alpha**X_A) % q
Y_B = (alpha**X_B) % q

# secret key calculation by Alice
K_A = (Y_B**X_A) % q

# secret key calculation by Bob
K_B = (Y_A**X_B) % q

print("(q, alpha): ", (q, alpha))
Exemple #20
0
else:
    for i in range(0, len(plaintext)):
        pt += str(ord(plaintext[i]))
    print(pt)


def modInverse(e, phin):
    e = e % phin
    for d in range(1, phin):
        if ((e * d) % phin == 1):
            return d
    return 1


import sympy
p = sympy.randprime(1000, 2000)
q = sympy.randprime(1000, 2000)

n = p * q

phin = (p - 1) * (q - 1)
list = []

for i in range(2, phin):
    if gcd(phin, i) == 1:
        list.append(i)

e = random.choice(list)

d = modInverse(e, phin)

def euclid(a, b):
    ost = a
    x, xx, y, yy = 1, 0, 0, 1
    while b:
        q = a // b
        a, b = b, a % b
        x, xx = xx, x - xx*q
        y, yy = yy, y - yy*q
    if y < 0:
        y += ost
    return y


q = sympy.randprime(1, 100)
p = sympy.randprime(1, 100)
while p == q:
    q = sympy.randprime(1, 100)
    p = sympy.randprime(1, 100)
r = q * p
phi = (p - 1) * (q - 1)
e = find_e(phi)
d = mod_inverse(e, phi)

print('Open key: ({}, {})'.format(e, r))

print("Enter string: ")
encrypted = input()
encrypted = encrypted.replace(' ', '')
Exemple #22
0
x = 8
n = 11
b = a ** x % n
print('a = ' + str(a))
print('x = ' + str(x))
print('b = ' + str(b))
print('n = ' + str(n))
solver = DLPS(a=a, b=b, n=n)
solver.printProblemOnFile(problemTitle='Problema 2 (x=' + str(x) + ').')
solver.solve()
solver.printSolutionsOnFile(problemTitle='Problema 2 (x=' + str(x) + ').')

print('###################################################################')

print('PROBLEM 3: Random Problem (n is a prime)')
a = sympy.randprime(10, 100)
x = sympy.randprime(10, 100)
n = sympy.randprime(100, 1000)
b = a ** x % n
print('a = ' + str(a))
print('x = ' + str(x))
print('b = ' + str(b))
print('n = ' + str(n))
solver = DLPS(a=a, b=b, n=n)
solver.printProblemOnFile(problemTitle='Problema 3 (x=' + str(x) + ').')
solver.solve()
solver.printSolutionsOnFile(problemTitle='Problema 3 (x=' + str(x) + ').')

print('###################################################################')

print('PROBLEM 4: Random Problem (n is a prime)')
def find_e(phi):
    x = sympy.randprime(1, phi)
    while math.gcd(x, phi) != 1:
        x = sympy.randprime(1, phi)
    return x
def encrypt(msg):
    #First do Vigenere cipher encryption
    msg1 = vigencrypt(msg)
    key = msg1[0]
    msg = msg1[1]
    distinct = []
    #Take 4 random numbers
    p = sympy.randprime(10, 40)
    distinct.append(p)
    q = sympy.randprime(10, 40)
    while (q in distinct):
        q = sympy.randprime(10, 40)
    distinct.append(q)
    r = sympy.randprime(10, 40)
    while (r in distinct):
        r = sympy.randprime(10, 40)
    distinct.append(r)
    s = sympy.randprime(10, 40)
    while (s in distinct):
        s = sympy.randprime(10, 40)
    distinct.append(s)
    # The second step is to compute n,m the product of p & q and r & s. In our case:
    n = p * q
    m = r * s
    # Next, we need to compute the Euler totient function for n,m,N \phi(n) which is
    # defined as \phi(n) = (p-1)*(q-1):
    N = n * m
    phi_n = (p - 1) * (q - 1)
    phi_m = (r - 1) * (s - 1)
    phi_N = phi_n * phi_m
    # Now we have to chose an exponent e that is relatively prime to
    # phi(n) = (p-1)*(q-1). The pair (e, n) becomes our public key that we use
    # to encrypt messages.
    e = sympy.randprime(10, phi_N)
    while (e in distinct):
        e = sympy.randprime(10, phi_N)
    distinct.append(e)
    # The next step is to calculate the value d for our private key
    d = mulinv(e, phi_N)
    # The pair (d,n) becomes private key and is only known to the receiver
    # Inorder to use an extra key Mu we will need n1,m1 with which we will calculate n1_inverse
    # and m1_inverse
    n1 = N // n
    m1 = N // m
    # n1_inverse and m1_inverse are calculated using the multiplicative inverse method with the
    # help of extended euclids algorithm.
    n1_inv = mulinv(n1, n)
    m1_inv = mulinv(m1, m)
    # We need another values k1,k2 to calculate k1_inverse and k2_inverse which are used to calculate Mu
    k1 = sympy.randprime(10, 40)
    while (k1 in distinct):
        k1 = sympy.randprime(10, 40)
    distinct.append(k1)
    k2 = sympy.randprime(10, 40)
    while (k2 in distinct):
        k2 = sympy.randprime(10, 40)
    distinct.append(k2)
    # k1_inverse and k2_inverse are also calculated using the multiplicative inverse method
    k1_inv = mulinv(k1, n)
    k2_inv = mulinv(k2, m)
    # calculate mu according to the formula
    mu = ((k1 * n1 * n1_inv) + (k2 * m1 * m1_inv))
    mu = mu % N
    encrypt_string = str(k1_inv) + " " + str(n) + " " + str(d)
    cipher_text = []
    for i in msg:
        #ct gets the cipher text value of the corresponding character
        ct = ((mu % N) * ((chton[i] % N)**e)) % N
        #ct gets appended to the cipher_text list which is used for decryption
        cipher_text.append(ct)
        encrypt_string = encrypt_string + " " + str(ct)
    return key + " " + encrypt_string
def public_exponent(_limit):
    return sympy.randprime(2, _limit)
Exemple #26
0
 def gen_prime(args):
     result = sympy.randprime(args[0], args[1])
     print("primes are genered")
     return result
Exemple #27
0
def get_big_prime(a=10**100, b=10**110):
    return sympy.randprime(a, b)
 def gen_pq(args):
     result = 5
     while (result - 3) % 4 != 0:
         result = sympy.randprime(args[0], args[1])
     return result
def generate_prime():
    n = sympy.randprime(MIN, MAX)
    return n
Exemple #30
0
def generate_prime(bitlength):
    a = '1' + '0' * (bitlength - 1)
    b = '1' * bitlength

    p = sympy.randprime(int(a, 2), int(b, 2))
    return p
Exemple #31
0
 def gen_p():
     return randprime(2 ** bits, 2 ** (bits + 1))
Exemple #32
0
import json
from sympy import randprime

e = 7
m = int(open('flag').read().strip().encode('hex'), 16)

for i in range(7):
    p = randprime(2 ** 256, 2 ** 257)
    q = randprime(2 ** 256, 2 ** 257)
    n = p * q
    assert m < n
    c = pow(m, e, n)
    print json.dumps({'n': n, 'e': e, 'c': c})
Exemple #33
0
def generate_prime_byte(n):
    prime_number = sympy.randprime(2**(8 * n - 1), 2**(8 * n))
    return int_to_byte(prime_number)