Demo entry 6344920

RSA

   

Submitted by anonymous on Jan 27, 2017 at 21:53
Language: Python. Code size: 1.5 kB.

import random
def generate_primes(maximum):
    if maximum < 3 or maximum >= 1000:
        print "Maximum must be at least 3 and less than 1000"

    primes = []
    numbers = [True] * maximum
    numbers[0] = False
    numbers[1] = False
    count = 2
    while count < maximum:
        for i in range(count + 1, maximum):
            if i % count == 0:
                numbers[i] = False
        count += 1

    for i, n in enumerate(numbers):
        if n:
            primes.append(i)
    return primes

def generate_keys():
    primes = generate_primes(99)
    p_i = random.randrange(len(primes))
    while True:
        q_i = random.randrange(len(primes))
        if q_i != p_i:
            break

    p = primes[p_i]
    q = primes[q_i]

    n = p * q

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

    while True:
        e_i = random.randrange(len(primes))
        e = primes[e_i]
        if phi_n % e != 0:
            break

    d = 2
    while True:
        if (d * e - 1) % phi_n == 0:
            break
        d+=1

    return p, q, d, e


def encrypt(message, n, e):
    return pow(message, e) % n

def decrypt(encrypted, n, d):
    return pow(encrypted, d) % n

print generate_primes(12)
print generate_primes(30)
print generate_primes(100)
p, q, d, e = generate_keys()
message = 47
encrypted = encrypt(message, p*q, e)
decrypted = decrypt(encrypted, p*q, d)
assert message == decrypted, "{} == {}, p: {} q: {} d: {} e: {}".format(message, decrypted, p,q,d,e)

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).