Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- import math
- import time
- def gcd(a, b):
- while b != 0:
- a, b = b, a % b
- return a
- def is_prime(num):
- if num == 2:
- return True
- if num < 2 or num % 2 == 0:
- return False
- for n in range(3, int(num ** 0.5) + 2, 2):
- if num % n == 0:
- return False
- return True
- def get_d(e,phi):
- d = 1.2
- k = 1
- while math.floor(d) != math.ceil(d):
- d = (k * phi + 1) / e
- k = k + 1
- return int(d)
- def generate_keypair(p, q):
- if not (is_prime(p) and is_prime(q)):
- raise ValueError('Both numbers must be prime.')
- elif p == q:
- raise ValueError('p and q cannot be equal')
- n = p * q
- phi = (p - 1) * (q - 1)
- e = random.randrange(1, phi)
- g = gcd(e, phi)
- while g != 1:
- e = random.randrange(1, phi)
- g = gcd(e, phi)
- d = get_d(e,phi)
- print("d = {} e = {} n = {}".format(d,e,n))
- return ((e, n), (d, n))
- def encrypt(pk, plaintext):
- # Unpack the key into it's components
- key, n = pk
- b = [(char.encode("cp1251")) for char in plaintext]
- с = [ord(i) for i in b]
- return [(char ** key) % n for char in с]
- def decrypt(pk, ciphertext):
- # Unpack the key into its components
- key, n = pk
- z = [ (i ** key) % n for i in ciphertext]
- return bytes(z).decode('cp1251')
- if __name__ == '__main__':
- '''
- Detect if the script is being run directly by the user
- '''
- print("RSA Encrypter/ Decrypter")
- start_time = time.time()
- p = 17 # int(input("Enter a prime number (17, 19, 23, etc): "))
- q = 37 #int(input("Enter another prime number (Not one you entered above): "))
- print("p = {} q = {}".format(p,q))
- print("Generating your public/private keypairs now . . .")
- public, private = generate_keypair(p, q)
- print("Your public key is ", public, " and your private key is ", private)
- message = "390 1037 583 1354 987" #input("Enter a message to encrypt with your private key: ")
- print("text to encript '{}'".format(message))
- encrypted_msg = encrypt(public, message)
- print("Your encrypted message is: ")
- print(''.join(map(lambda x: str(x), encrypted_msg)))
- print("Decrypting message with public key ", public, " . . .")
- print("Your message is:")
- s = decrypt(private, encrypted_msg)
- print( s)
- time_elapsed = time.time() - start_time
- print('Time of RSA5 %.9f' % (time_elapsed))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement