-
Notifications
You must be signed in to change notification settings - Fork 8
/
Rsa.py
127 lines (62 loc) · 1.87 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
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
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import random
class Rsa:
def __init__(self,p,q,e,inputText):
self.e = e
self.p = p
self.q = q
self.fi = (self.p-1)*(self.q-1)
self.n = self.p*self.q
self.inputText = inputText
def Gcd(self,fi,e):
if e == 0:
return 0,1
else:
y,x = self.Gcd(e,fi%e)
return x-(fi//e)*y,y
def FastExpMod(self,baseNumber, e, mod):
result = 1
while e != 0:
if (e&1) == 1:
result = (result * baseNumber) % mod
e >>= 1
baseNumber = (baseNumber*baseNumber) % mod
return result
def PrivateKey(self):
s = self.Gcd(self.fi,self.e)
if s[0] > 0:
key = s[0]
else:
key = s[1]
return key
def DealNumber(self,num,need):
if need - len(num) != 0:
num = '0'*(need-len(num)) + num
return num
def DealText(self,text):
return ''.join([self.DealNumber(str(ord(i)-97),2) for i in text])
def CreateRandomNumber(self,start,end):
return random.randint(start,end)
def Encode(self):
getInputText = self.DealText(self.inputText)
return ''.join([self.DealNumber(str(self.FastExpMod(int(getInputText[i*4:(i+1)*4]),self.e,self.n)),4) for i in range(len(getInputText)/4)])
def Decode(self,encryptText):
privateKey = self.PrivateKey()
getText = ''.join([self.DealNumber(str(self.FastExpMod(int(encryptText[i*4:(i+1)*4]),privateKey,self.n)),4) for i in range(len(encryptText)/4)])
return ''.join([chr(97 + int(getText[i*2:(i+1)*2])) for i in range(len(getText)/2)])
def main():
p=43
q=59
e=13
#if wanted to get the random num for p,q,e,you call use the function I have written in the class rsa
#its name is CreateRandomNumber()
text = 'public'
rsa = Rsa(43,59,13,text)
print "Text:" + text
encryptText = rsa.Encode()
print "Encrypt:" + encryptText
decryptText = rsa.Decode(encryptText)
print "Decrypt:" + decryptText
if __name__ == '__main__':
main()