Repository navigation
Expand file tree
/
Copy pathrsaAlgorithmFunctions.py
More file actions
180 lines (144 loc) · 4.98 KB
/
Copy pathrsaAlgorithmFunctions.py
File metadata and controls
180 lines (144 loc) · 4.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# Algorithm functions for RSA Encryption Algorithm
'''
Functions for RSA
- Extended Euclidean Algorithm
- Modular Inverse
- Miller-Rabin Primality Test
- Random Large Prime Generator
- Private & Public Key Generator
- Encryption
- Decyrption
'''
# Import libraries and necessary Functions
import random
# Extended Euclidean Algorithm (Results in GCD and Bézout Coefficients)
def extEucAlg(a, b):
if a == 0:
return b, 0, 1
gcdVal, x1, y1 = extEucAlg(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcdVal, x, y
# Use Extended Euclidean Algorithm to find Modular Inverse
def modInv(a, m):
# Find positive modular inverse using extEucAlg
gcdVal, x, _ = extEucAlg(a, m)
# Check if gcd is 1
if gcdVal != 1:
raise ValueError(f"No modular inverse exists when a = {a} and m = {m}")
# Make sure result is positive
return (x % m + m) % m
# Miller-Rabin Primality Test
def primeTest(n, k = 5):
# Check if 2 (True), 3 (True), even (False), 1 or less (False)
if n == 2 or n == 3:
return True
if n <= 1 or n%2 == 0:
return False
# Rewrite n-1 as 2^r * d
r = 0
d = n-1
while d%2 == 0:
d //= 2
r += 1
# Test with k bases
for _ in range(k):
a = random.randrange(2, n-1)
x = pow(a, d, n)
# Check if x = 1 or x = n-1 (Allowed if n is prime)
if x == 1 or x == n-1:
continue
# Check if x = n-1 for squares of x (Should occur if n is prime)
for _ in range(r-1):
x = pow(x, 2, n)
if x == n-1:
break
else:
return False
# With k = 5, error probability is 1/1024
return True
# Generate Prime (Optional Strong Prime) with Specified Bit Length
def genPrime(bits = 512, strong = False):
# Generate Strong Prime (p = 2rq + 1 where q is prime)
if strong:
# Create prime q around half the size of p
qBits = (bits-1) // 2
while True:
q = genPrime(qBits, strong=False)
# Create odd integer r
r = random.getrandbits(bits-qBits-1) | 1
# Ensure p-1 = 2*r*q, and thus is resistant to Pollard’s p–1 algorithm
p = (2*r*q)+1
if p.bit_length() == bits and primeTest(p):
return p
# Generate Normal Prime
else:
while True:
# Generate random number of specified bit length
p = random.getrandbits(bits)
# Ensure it's odd (LSB is 1) and has the correct bit length (MSB is 1)
p |= (1 << (bits-1)) | 1
if primeTest(p):
return p
# Generate Key Pair with Specified Bit Length
def genKeyPair(bits = 1024, strong = False):
# Generate two distinct primes (Each half bit length)
p = genPrime(bits // 2, strong)
q = genPrime(bits // 2, strong)
# Ensure p and q are different
while q == p:
q = genPrime(bits // 2, strong)
# Calculate n (full bit length) and φ(n)
n = p*q
phi = (p-1)*(q-1)
# Choose public exponent e
e = 65537
if extEucAlg(e, phi)[0] != 1:
e = 3
while extEucAlg(e, phi)[0] != 1:
e += 2
# Calculate private exponent d
d = modInv(e, phi)
# Returns (Public Key, Private Key) as tuples (e, n), (d, n)
return (e, n), (d, n)
# Encryption Function
def encrypt(message, publicKey):
e, n = publicKey
# Calculate maximum block size in bytes and ensure that the integer representation of the block is < n
maxBytes = (n.bit_length() - 1) // 8
# Convert message to bytes
messageBytes = message.encode("utf-8")
# Encyrpted message list
encryptedMessage = []
# Process message in blocks
for i in range(0, len(messageBytes), maxBytes):
# Get block of bytes
block = messageBytes[i:i + maxBytes]
# Convert bytes to integer (MSB First)
blockInt = int.from_bytes(block, byteorder = "big")
# Encrypt the block
encryptedBlock = pow(blockInt, e, n)
encryptedMessage.append(encryptedBlock)
return encryptedMessage
# Decryption Function
def decrypt(encryptedMessage, privateKey):
d, n = privateKey
# Set up byte string
decryptedBytes = b''
# Process each encrypted block
for block in encryptedMessage:
# Decrypt the block
decryptedInt = pow(block, d, n)
# Calculate the number of bytes needed to represent block
byteLength = (decryptedInt.bit_length() + 7) // 8
# If 0, byteLength = 1
if byteLength == 0:
byteLength = 1
# Convert integer to bytes (MSB First)
blockBytes = decryptedInt.to_bytes(byteLength, byteorder = "big")
decryptedBytes += blockBytes
# Convert bytes back to string (Show hex form if decyrption fails)
try:
return decryptedBytes.decode('utf-8')
except UnicodeDecodeError as e:
return f"Decoding Error: {decryptedBytes.hex()}"