-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRSA.py
77 lines (69 loc) · 1.88 KB
/
RSA.py
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
import numpy as np
import math
import random
def isPrime(k):
for i in range(2,math.ceil(k**0.5)):
if not k%i:
return False
return True
def generateKeys(m=10):
maxi = int("9"*m)
mini = 10**(m-1)
primes = [i for i in range(mini,maxi) if isPrime(i)]
p = random.choice(primes)
while True:
q = random.choice(primes)
if p!=q:
break
n = p*q
phi = (p-1)*(q-1)
for e in range(2,phi):
if math.gcd(e,phi) == 1:
break
k = 1
d = 0
while True:
r = k*phi + 1
if r/e == r//e:
d = r // e
break
k+=1
return n,e,d
def EncryptMessage(publicKey,message):
n,e = publicKey
print(n)
encrypted = ""
for i in message:
encrypted+= chr(pow(ord(i),e,n))
return encrypted
def DecryptMessage(publicKey,privateKey,message):
n,e = publicKey
decrypted = ""
for i in message:
decrypted += chr(pow(ord(i),privateKey,n))
return decrypted
def EncryptFile(publicKey,infilename,outfilename = "Encrypted.txt"):
try:
with open(infilename) as infile:
with open(outfilename) as outfile:
for line in infile:
outfile.write(EncryptMessage(publicKey,line))
return True
except:
return False
def DecryptFile(publicKey,privateKey,infilename,outfilename = "Decrypted.txt"):
try:
with open(infilename) as infile:
with open(outfilename) as outfile:
for line in infile:
outfile.write(DecryptMessage(publicKey,privateKey,line))
return True
except:
return False
if __name__=="__main__":
n,e,d = generateKeys(2)
print(n,e,d)
message = "Test Message"
Encrypted = EncryptMessage((n,e),message)
print(Encrypted)
print(DecryptMessage((n,e),d,Encrypted))