Amazing-Python-Scripts

Форк
0
70 строк · 1.6 Кб
1
import math
2
import random
3

4

5
# Arguments provide range to generate two prime numbers
6
def primenumbers(srt, n):
7
    primenos = []
8
    prime = [True for i in range(n + 2 - srt)]
9
    prime[0] = False
10
    prime[1] = False
11
    for p in range(srt, int(math.sqrt(n)) + 1):
12
        if prime[p] == True:
13
            for i in range(p * p, n + 1, p):
14
                prime[i] = False
15
    for p in range(srt, n + 1):
16
        if prime[p]:
17
            primenos.append(p)
18
    P = random.choice(primenos)
19
    primenos.remove(P)
20
    Q = random.choice(primenos)
21
    return (P, Q)
22

23

24
# RSA Algorithm Implementation:
25
print("RSA Implementation starts for the connection")
26
for c in range(5):
27
    print("------")
28

29
p, q = primenumbers(1, 30)
30
N = p * q
31
f = (p - 1) * (q - 1)
32

33

34
# Generate Public Key for Encryption
35
def publickey():
36
    for i in range(2, f):
37
        if math.gcd(f, i) == 1:
38
            E = i
39
            break
40
    return E
41

42

43
E = publickey()
44

45

46
def privatekey():
47
    for j in range(1, N):
48
        if math.fmod((E * j), (f)) == 1:
49
            # if (E * j) % (f) == 1:
50
            D = j
51
            break
52
    return D
53

54

55
D = privatekey()
56
print("Generated Public Key for Encryption E: ", E)
57
print("Generated Private Key for Decryption D: ", D)
58
Plain_text = float(input("Enter Plain text in numerical data type: \n"))
59

60
x = math.pow(Plain_text, E)
61
Cipher_text = math.fmod(x, N)
62
print("Generated Cipher Text using Public Key: ", Cipher_text)
63

64
D_user = int(input("Enter your private key for Decryption \n"))
65
if D_user == D:
66
    y = math.pow(Cipher_text, D)
67
    Decrypted_text = math.fmod(y, N)
68
    print("The Cipher Text has been decrypted: ", Plain_text)
69
else:
70
    print("ENTERED WRONG PRIVATE KEY")
71

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.