Ejemplo n.º 1
0
def getStrongPrime(N):
    """ Génère un nombre premier p de N bits de tel sorte que :
    (p-1)/2 = q et q aussi premier """
    p = getPrime(N)
    while not miller_rabin((p - 1) // 2):
        p = getPrime(N)
    return p
Ejemplo n.º 2
0
def generate_primes(bitsize):
    while True:
        p = number.getPrime(bitsize, randfunc=Random.get_random_bytes)
        q = number.getPrime(bitsize, randfunc=Random.get_random_bytes)
        ## Make sure the big primes are not equal + ensure
        if (p != q) and ((p % 4) == 3) and ((q % 4) == 3):
            return (p, q)
Ejemplo n.º 3
0
def Keys():
    p = number.getPrime(64, randfunc=Cryptodome.Random.get_random_bytes)
    q = number.getPrime(64, randfunc=Cryptodome.Random.get_random_bytes)
    e = number.getPrime(128, randfunc=Cryptodome.Random.get_random_bytes)
    N = p * q
    PHI = (p - 1) * (q - 1)
    d = modinv(e, PHI)
    return [str(e), str(d), str(N)]
Ejemplo n.º 4
0
    def keygen(security_param=2048):
        p = number.getPrime(security_param // 2)
        q = number.getPrime(security_param // 2)

        key_encryptor = KeyEncryptor.get_instance()
        key_coder = RabinKeyCoder()
        public_key = key_coder.encode_public_key(p * q)
        private_key = key_encryptor.encrypt(key_coder.encode_private_key(p, q))

        return public_key, private_key
Ejemplo n.º 5
0
    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)
Ejemplo n.º 6
0
    def __init__(self, key_length):
        self.e=3
        o=0

        while gcd(self.e, o)!=1:
            p, q = getPrime(key_length//2), getPrime(key_length//2)
            o = nok(p-1, q-1)
            self.n=p*q

        self._d=invmod(self.e, o)
Ejemplo n.º 7
0
    def __init__(self, key_length):
        self.e = 3
        euler = 0

        while greatest_common_divisor(self.e, euler) != 1:
            p, q = getPrime(key_length // 2), getPrime(key_length // 2)
            euler = (p - 1) // greatest_common_divisor((p - 1),
                                                       (q - 1)) * (q - 1)
            self.n = p * q

        self.mod = inversion_by_mod(self.e, euler)
Ejemplo n.º 8
0
def main_RSA():
    # /!\ ec.H returns a 256-bit hash, n & nf have to be at least that large.

    ## Alice's key
    p = getPrime(1<<8)
    q = getPrime(1<<8)
    e = 65537                  # public
    d = invmod(e,(p-1)*(q-1))  # private
    n = p*q                    # modulus
    msg = b'Everybody knows the captain lied'
    h = ec.H(msg)
    sig = pow(h,d,n)        # sign
    assert pow(sig,e,n)==h  # verify

    ## Attack
    # we want to find e such s^e = h mod nf, for some nf = pf*qf
    # i.e. s^e = h mod pf and s^e = h mod qf
    print('Sieving...', end=' ', flush=True)
    Primes = sieve(1<<14)
    print('ok.')
    pf,Pf = gen_smooth_prime(Primes, sig,h, 1<<8)
    Primes = [r for r in Primes if r not in Pf]  # filter out primes from pf-1
    qf,Qf = gen_smooth_prime(Primes, sig,h, 1<<8)

    nf = pf*qf

    # /!\ pf-1 and qf-1 are not coprime: they have a factor 2 in common.
    # The congruential system will have a solution iff they are
    # compatible on that factor, i.e. e_pf = e_qf mod 2
    # where e_pf is such that
    # sig^((pf-1)//2 * e_pf) = h^((pf-1)//2) mod pf
    # with sig and h primitive roots mod pf.
    # But if e_pf = 0 mod 2, then h^((pf-1)//2) = 1 mod pf,
    # contradicting the fact that h is a primitive root.
    # Hence the only possibility is
    # e_pf = 1 mod 2 and similarly e_qf = 1 mod 2
    # They are always compatible and there exists a unique solution
    # e mod (pf-1)*(qf-1)//2

    print('DL solving...', end=' ', flush=True)
    epf,emodp = DL_solve(sig,h, pf,Pf)
    eqf,emodq = DL_solve(sig,h, qf,Qf[1:])  # skip 2
    ef,emod = CRT_combine(epf,emodp, eqf,emodq)
    assert emodp==pf-1 and emodq==(qf-1)//2 and emod==(pf-1)*(qf-1)//2
    print('ok.')

    # Forged key: (ef,df,nf)
    df = invmod(ef, (pf-1)*(qf-1))  # private key (unused here)
    print('Verifying with forged RSA key...', end=' ', flush=True)
    assert pow(sig,ef,nf)==h  # verify
    print('ok.')
Ejemplo n.º 9
0
def gen_key(size=1<<10):
    e = 3  # we always want e = 3 here
    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)
    K = (e, n)
    k = (d, n)
    return (k, K)
Ejemplo n.º 10
0
 def __init__(self):
     self.n = getPrime(8*8, randfunc=get_random_bytes)
     self.m = int.from_bytes(get_random_bytes(8), byteorder="big") % self.n
     self.c = int.from_bytes(get_random_bytes(8), byteorder="big") % self.n
     self.state = int.from_bytes(get_random_bytes(8), byteorder="big") % self.n
     for _ in range(randint(128, 1024)):
         self.state = self.next()
Ejemplo n.º 11
0
def generate():
    f = True
    n_length = int(input("\nIntroduce the length of your key (2048 bytes common and faster / 4096 bytes safest): "))
    while f:
        e = 65537
        p = num.getPrime(n_length//2)
        q = num.getPrime(n_length//2)
        n = p*q
        phi = (p-1)*(q-1)
        if phi % e == 0:
            pass
        else:
            break
    #print(f"Your p number is: {p}\nYour q number is: {q}\nYour modulus is: {n}\nPhi is: {phi}")
    d = euclidean(phi, e)
    #print(f"Your e number is {e}")
    #print(f"Your d number is {d}")

    m = randint(5000,9000)
    c = (m**e) % n
    dec = fast_exp(c,d,n)
    if dec != m:
        print("ALERT, SOMETHING WENT WRONG, GENERATE YOUR KEYS AGAIN")
        return 0
    rsaKey = RSA.construct((n, e))

    pubKey = rsaKey.export_key()
    pubKey = pubKey.decode('ascii')
    comps = [n, e, d]
    privrsaKey = RSA.construct(comps);
    privKey = privrsaKey.export_key()
    privKey = privKey.decode('ascii')
    print("This are your keys: \n")
    print(f"\n{pubKey}")
    print(f"\n{privKey}")
    do = input("\n\nDo you wish to export them?\n Introduce y (yes) or n (no): ")
    while (do != 'y') and (do != 'n'):
        do = input("\n\nDo you wish to export them?")
    if do == 'y':
        text_file = open("pubKey.txt", 'wt')
        text_file.write(pubKey)
        text_file.close()
        text_file = open("privKey.txt", 'wt')
        text_file.write(privKey)
        text_file.close()
    if do == 'n':
        return 0
def RandomPrime(
        bits,
        prime=0
):  #this function returns a random prime that is larger than 258
    while prime < 258:  # While prime isn't large enough for RSA...
        prime = number.getPrime(
            1024)  # Change prime to random value created through getPrime
    return (prime)  # Return that prime
Ejemplo n.º 13
0
    def test_getPrime(self):
        """Util.number.getPrime"""
        self.assertRaises(ValueError, number.getPrime, -100)
        self.assertRaises(ValueError, number.getPrime, 0)
        self.assertRaises(ValueError, number.getPrime, 1)

        bits = 4
        for i in range(100):
            x = number.getPrime(bits)
            self.assertEqual(x >= (1 << bits - 1), 1)
            self.assertEqual(x < (1 << bits), 1)

        bits = 512
        x = number.getPrime(bits)
        self.assertNotEqual(x % 2, 0)
        self.assertEqual(x >= (1 << bits - 1), 1)
        self.assertEqual(x < (1 << bits), 1)
Ejemplo n.º 14
0
def blum_blum_generator():
    p = number.getPrime(512)
    while p % 4 != 3:
        p = number.getPrime(512)
    q = number.getPrime(512)
    while q % 4 != 3:
        q = number.getPrime(512)

    n = p * q
    l = pow(2, 10)
    s = int(time.time())
    x = [pow(s, 2) % n]
    output = chr(x[0] % 2 + ord("0"))
    for i in range(1, l):
        x.append(pow(x[i - 1], 2) % n)
        output += chr(x[i] % 2 + ord("0"))
    return output
Ejemplo n.º 15
0
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)
Ejemplo n.º 16
0
    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
Ejemplo n.º 17
0
def encrypt(x):
    """
    docstring
    """
    k = Crypto_Number.getPrime(bits-1,randfunc=Crypto_Rand.get_random_bytes)
    y1 = pow(alpha,k,p)
    y2 = (x*pow(beta,k))%p

    return y1,y2
Ejemplo n.º 18
0
Archivo: RSA.py Proyecto: macgia99/Code
def ChooseKeys(choice=1,file=Private_file,file2=Public_file):
    """
    This function generate pubic key and private key
    """
    p,q = None,None
    if choice == 1:
        # Auto generate p, q then calculate n, totient (Choice 1)
        p = Crypto_Number.getPrime(bits, randfunc=Crypto_Rand.get_random_bytes)
        q = p
        while q == p:
            q = Crypto_Number.getPrime(bits, randfunc=Crypto_Rand.get_random_bytes)
    else:
        # Auto  calculate n, totient (Choice 2)
        p = int(input("p = "))
        q = p
        while p == q:
            q = int(input("q = "))
    
    n = p * q
    totient = (p - 1) * (q - 1)
    # generate e
    e = ChooseE(totient)
    # calculate d
    d = Module.egcd(e,totient)
    # save to file 
    ## Private key
    try:
        with open(file,'w+') as pri_file:
            pri_file.write(str(n)+'\n')
            pri_file.write(str(d)+'\n')
            pri_file.close()
    except IOError or FileExistsError or FileNotFoundError:
        print("Can't write to file!!!")
        print(traceback.format_exc()) # for debug
        
    ## Public key 
    try:
        with open(file2, 'w+') as pub_file:
            pub_file.write(str(n)+'\n')
            pub_file.write(str(e)+'\n')
            pub_file.close()
    except IOError or FileExistsError or FileNotFoundError:
        print("Can't write to file!!!")
        print(traceback.format_exc())
Ejemplo n.º 19
0
 def _generate_prime(self) -> int:
     """
     Helper function to generate a prime number from the instance variable n_bits, raises an error if this is not
     set. n_bits is either set when an instance is initialized or when a prime is loaded from binary data.
     """
     if self.n_bits is None:
         raise ValueError("n_bits is not specified, cannot generate prime. Either specify n_bits or use read "
                          "function to import prime from file")
     print(f"Generating prime with {self.n_bits} bits...")
     return number.getPrime(self.n_bits)
Ejemplo n.º 20
0
def rsa(m):
    p, q = 0, 0
    while not (q < p < 2 * q):
        p = number.getPrime(514)
        q = number.getPrime(514)
    n = p * q
    e = 65537
    v_phi = (p - 1) * (q - 1)
    g, x, y = euclid_extins(e, v_phi)
    d = x % v_phi

    c = pow(m, e, n)

    start_time = time.time()
    dec = pow(c, d, n)
    elapsed_time = time.time() - start_time

    print("Mesaj: " + str(m))
    print("Mesaj criptat: " + str(c))
    print("Mesaj decriptat: " + str(dec))

    print("Timp de executie pentru decriptarea obisnuita: ")
    print("%s secunde" % elapsed_time)

    start_time = time.time()
    dec_crt = rsa_crt_dec(d, p, q, c)
    elapsed_time = time.time() - start_time
    print("\nMesaj decriptat cu CRT: " + str(dec_crt))

    print("Timp de executie pentru decriptarea cu TCR: ")
    print("%s secunde" % elapsed_time)

    d = n
    while math.gcd(d, v_phi) != 1 or 81 * (d**4) >= n:
        d = number.getRandomNBitInteger(32)
    g, x, y = euclid_extins(d, v_phi)
    e = x % v_phi
    print("Actual p and q: " + str(p) + " " + str(q))
    print("Actual d: " + str(d))
    wiener_attack(n, e)
Ejemplo n.º 21
0
def keygen_dh(key_size, use_group, dh_group, dh_mod_size, dh_p, dh_g):
    if use_group == True:
        dh_p = modp_groups[dh_group]['p']
        dh_g = modp_groups[dh_group]['g']
        dh_mod_size = size(dh_p)
    else:
        # check parameters, assign defaults if necessary
        if dh_p != None:
            dh_mod_size = size(dh_p)

        # print('###########:', key_size, dh_mod_size, flush = True)
        # generate new safe prime to define finite field
        # This is pretty efficient
        if dh_p == None:
            dh_p = 0
            count = 0
            while not isPrime(dh_p):
                count += 1
                q = getPrime(dh_mod_size - 1)
                dh_p = (2 * q) + 1
            #print('Fresh q:', count, q, flush = True)
            #print('Fresh p:', count, dh_p, flush = True)

        #define new generator for the finite field
        if dh_g == None:
            dh_g = 2
            generator_found = False
            count2 = 0
            while (generator_found == False) and (dh_g < dh_p):
                count2 += 1
                generator_found = True
                #print('&&&&&&&&&&:', count2, 1)
                if pow(dh_g, 2, dh_p) == 1:
                    generator_found = False
                    #print('&&&&&&&&&&:', count2, 2)
                if generator_found == True and pow(dh_g, q, dh_p) == 1:
                    generator_found = False
                    #print('&&&&&&&&&&:', count2, 3)
                if generator_found == False:
                    dh_g += 1
                    #print('&&&&&&&&&&:', count2, 4)
            #print('Fresh g:', count2, dh_g)
    #DH Group Parameters have now been established

    #generate new exponent (secret key derivation value)
    dh_x = getRandomNBitInteger(key_size)

    #generate dh_X = dh_g ** dh_x (mod dh_p) (public key derivation value)
    dh_X = pow(dh_g, dh_x, dh_p)

    #first value must remain secret, the rest is public
    return (dh_x, dh_X, dh_g, dh_p)
Ejemplo n.º 22
0
def jacobi_generator():
    false_pos_prob = 0.000000000000000000000001
    p = number.getPrime(512)
    while not (number.isPrime(p, false_pos_prob)) or p % 4 != 3:
        p = number.getPrime(512)
    q = number.getPrime(512)
    while not (number.isPrime(q, false_pos_prob)) or q % 4 != 3:
        q = number.getPrime(512)
    n = p * q
    l = pow(2, 10)
    a = int(time.time() * 1000)
    while math.gcd(a, n) != 1:
        a = int(time.time())
    output = ""
    for i in range(1, l):
        jacobi_symbol = jacobi(a + i, n)
        if jacobi_symbol == 0:
            return "error"
        if jacobi_symbol == -1:
            jacobi_symbol = 0
        output += chr(jacobi_symbol + ord("0"))
    return output
Ejemplo n.º 23
0
def main():
    # p = 329263086039022862010758005107860925059
    # q = 312629737368228721811040745580846410531
    # e = 17684950237965090779
    p = getPrime(KEY_SIZE)
    q = getPrime(KEY_SIZE)
    e = getPrime(E_SIZE)
    print(f'p: {p}, q: {q}, e: {e}')

    print()

    public_key, private_key = generate_keypair(p, q, e)
    print(f'pub_key: {public_key}')
    print(f'pri_key: {private_key}')

    print()

    msg = b'easy rsa!'

    ciphertext = encrypt(public_key, msg)
    print(f'ciphertext: {ciphertext}')

    plaintext = decrypt(private_key, ciphertext)
    print(f'plaintext: {plaintext}')
Ejemplo n.º 24
0
def generate_keypair(p, q, e=0):
    assert p != q
    assert isPrime(p) and isPrime(q)

    n = p * q

    phi = (p - 1) * (q - 1)

    if not e:
        e = getPrime(E_SIZE)
    assert e < phi

    # e & phi co-prime
    g, _, _ = egcd(e, phi)
    assert g == 1

    d = modular_inverse(e, phi)

    # Public key: (n, e), Private key: (n, d)
    return ((n, e), (n, d))
Ejemplo n.º 25
0
    def test(tcount, bits=256):
        n = getPrime(int(bits / 8))
        #n = rsa.get_prime(bits / 8, 20)
        p = randint(1, n)
        p1 = (randint(1, n), randint(1, n))
        q = curve_q(p1[0], p1[1], p, n)
        p2 = mulp(p, q, n, p1, randint(1, n))

        c1 = [randint(1, n) for i in range(tcount)]
        c2 = [randint(1, n) for i in range(tcount)]
        c = list(zip(c1, c2))

        t = time.time()
        for i, j in c:
            from_projective(
                addf(p, q, n, mulf(p, q, n, to_projective(p1), i),
                     mulf(p, q, n, to_projective(p2), j)), n)
        t1 = time.time() - t
        t = time.time()
        for i, j in c:
            muladdp(p, q, n, p1, i, p2, j)
        t2 = time.time() - t

        return tcount, t1, t2
Ejemplo n.º 26
0
    def test(tcount, bits=256):
        n = getPrime(int(bits/8))
        #n = rsa.get_prime(bits / 8, 20)
        p = randint(1, n)
        p1 = (randint(1, n), randint(1, n))
        q = curve_q(p1[0], p1[1], p, n)
        p2 = mulp(p, q, n, p1, randint(1, n))

        c1 = [randint(1, n) for i in range(tcount)]
        c2 = [randint(1, n) for i in range(tcount)]
        c = list(zip(c1, c2))

        t = time.time()
        for i, j in c:
            from_projective(addf(p, q, n,
                                 mulf(p, q, n, to_projective(p1), i),
                                 mulf(p, q, n, to_projective(p2), j)), n)
        t1 = time.time() - t
        t = time.time()
        for i, j in c:
            muladdp(p, q, n, p1, i, p2, j)
        t2 = time.time() - t

        return tcount, t1, t2
Ejemplo n.º 27
0
def initialization(nbit):
    p = number.getPrime(nbit, os.urandom)
    q = number.getPrime(nbit, os.urandom)
    n = p * q
    phi = (p - 1) * (q - 1)
    return n, phi
Ejemplo n.º 28
0
# Reconstruct the y-coordinate when curve parameters, x and the sign-bit of
# the y coordinate are given:
def y_from_x(x, p, q, n, sign):
    """Return the y coordinate over curve (p, q, n) for given (x, sign)"""

    # optimized form of (x**3 - p*x - q) % n
    a = (((x * x) % n - p) * x - q) % n


if __name__ == "__main__":
    from Cryptodome.Random.random import randint
    from Cryptodome.Util.number import getPrime
    import time

    t = time.time()
    n = getPrime(int(256 / 8))
    #n = rsa.get_prime(256 / 8, 20)
    tp = time.time() - t
    p = randint(1, n)
    p1 = (randint(1, n), randint(1, n))
    q = curve_q(p1[0], p1[1], p, n)
    r1 = randint(1, n)
    r2 = randint(1, n)
    q1 = mulp(p, q, n, p1, r1)
    q2 = mulp(p, q, n, p1, r2)
    s1 = mulp(p, q, n, q1, r2)
    s2 = mulp(p, q, n, q2, r1)
    # s1 == s2
    tt = time.time() - t

    def test(tcount, bits=256):
Ejemplo n.º 29
0
 def getprimewithseed(self, bit, seed):
     random.seed(seed)
     return number.getPrime(bit, self._randfunc)
Ejemplo n.º 30
0
 def __init__(self):
     self.p = number.getPrime(BITS)
     self.a = random.getrandbits(BITS) % self.p
     self.g = 2
     self.bibsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.bibsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Ejemplo n.º 31
0
from Cryptodome.Util.number import bytes_to_long, long_to_bytes
import Crypto_module as Module
from Crypto_module import clear
from Cryptodome.Util import number as Crypto_Number
from Cryptodome import Random as Crypto_Rand
#Define
bits = 10
p = Crypto_Number.getPrime(bits,randfunc=Crypto_Rand.get_random_bytes)
alpha = 2
a = Crypto_Number.getRandomInteger(bits-1,randfunc=Crypto_Rand.get_random_bytes)
beta = pow(alpha,a,p)
#encrypt
def encrypt(x):
    """
    docstring
    """
    k = Crypto_Number.getPrime(bits-1,randfunc=Crypto_Rand.get_random_bytes)
    y1 = pow(alpha,k,p)
    y2 = (x*pow(beta,k))%p

    return y1,y2

def Decrypt(y1,y2):
    """
    docstring
    """
    t1  = pow(y1,alpha,p)
    t2  = Module.egcd(t1,p)

    x = (y2*t2)%p
Ejemplo n.º 32
0
# Reconstruct the y-coordinate when curve parameters, x and the sign-bit of
# the y coordinate are given:
def y_from_x(x, p, q, n, sign):
    """Return the y coordinate over curve (p, q, n) for given (x, sign)"""

    # optimized form of (x**3 - p*x - q) % n
    a = (((x * x) % n - p) * x - q) % n


if __name__ == "__main__":
    from Cryptodome.Random.random import randint
    from Cryptodome.Util.number import getPrime
    import time

    t = time.time()
    n = getPrime(int(256/8))
    #n = rsa.get_prime(256 / 8, 20)
    tp = time.time() - t
    p = randint(1, n)
    p1 = (randint(1, n), randint(1, n))
    q = curve_q(p1[0], p1[1], p, n)
    r1 = randint(1, n)
    r2 = randint(1, n)
    q1 = mulp(p, q, n, p1, r1)
    q2 = mulp(p, q, n, p1, r2)
    s1 = mulp(p, q, n, q1, r2)
    s2 = mulp(p, q, n, q2, r1)
    # s1 == s2
    tt = time.time() - t

    def test(tcount, bits=256):