Amazing-Python-Scripts
70 строк · 1.6 Кб
1import math
2import random
3
4
5# Arguments provide range to generate two prime numbers
6def primenumbers(srt, n):
7primenos = []
8prime = [True for i in range(n + 2 - srt)]
9prime[0] = False
10prime[1] = False
11for p in range(srt, int(math.sqrt(n)) + 1):
12if prime[p] == True:
13for i in range(p * p, n + 1, p):
14prime[i] = False
15for p in range(srt, n + 1):
16if prime[p]:
17primenos.append(p)
18P = random.choice(primenos)
19primenos.remove(P)
20Q = random.choice(primenos)
21return (P, Q)
22
23
24# RSA Algorithm Implementation:
25print("RSA Implementation starts for the connection")
26for c in range(5):
27print("------")
28
29p, q = primenumbers(1, 30)
30N = p * q
31f = (p - 1) * (q - 1)
32
33
34# Generate Public Key for Encryption
35def publickey():
36for i in range(2, f):
37if math.gcd(f, i) == 1:
38E = i
39break
40return E
41
42
43E = publickey()
44
45
46def privatekey():
47for j in range(1, N):
48if math.fmod((E * j), (f)) == 1:
49# if (E * j) % (f) == 1:
50D = j
51break
52return D
53
54
55D = privatekey()
56print("Generated Public Key for Encryption E: ", E)
57print("Generated Private Key for Decryption D: ", D)
58Plain_text = float(input("Enter Plain text in numerical data type: \n"))
59
60x = math.pow(Plain_text, E)
61Cipher_text = math.fmod(x, N)
62print("Generated Cipher Text using Public Key: ", Cipher_text)
63
64D_user = int(input("Enter your private key for Decryption \n"))
65if D_user == D:
66y = math.pow(Cipher_text, D)
67Decrypted_text = math.fmod(y, N)
68print("The Cipher Text has been decrypted: ", Plain_text)
69else:
70print("ENTERED WRONG PRIVATE KEY")
71