RSA
MyMath.py: Chứa hàm toán học
PrimeTest.py: Chứa hàm kiểm tra tính nguyên tố
GenePrime.py: Chương trình sinh nguyên tố xác suất
CreateKey.py: Tạo khóa cho mã hóa RSA
MyBase.py: Đổi cơ số
encode.py: Chương trình mã hóa văn bản
decode.py: Chương trình giải mã văn bản
powMod(a, b, m)
a^b mod m
Code:
def powMod(a, b, m):
x = []
while b != 0:
x.append(b & 1)
b = b >> 1
sz = len(x)
po = [a%m]
for i in range(1,sz):
p = (po[i-1]*po[i-1])%m
po.append(p)
r = 1
for i in range(sz):
if(x[i] != 0):
r*= po[i]
r%= m
return r
UCLN(a, b)
def GCD(a, b):
if b == 0:
return a
return GCD(b, a%b)
x*a + y*b = z = UCLN(a, b)
def GCD_extended(a, b):
u1, u2, u3 = 1, 0, a
v1, v2, v3 = 0, 1, b
while v3 != 0:
q = u3//v3
t1, t2, t3 = u1 - q*v1, u2 - q*v2, u3 - q*v3
u1, u2, u3 = v1, v2, v3
v1, v2, v3 = t1, t2, t3
return u1, u2, u3
a^(p-1) ≡ 1(mod p)
(p: số nguyên tố và a không chia hết cho p)
def Fermat(p,x):
for i in range(x):
a = sprime[i]
if MyMath.powMod(a,p-1,p) != 1:
return False
return True
Miller_Rabin(p, x):
n-1 =2^s*m
, n trải qua Miller cơ sở b nếu b^t ≡ 1 mod n
hoặc b^((2^j)t) ≡ -1 mod n
với j nào đó 0 ≤ j ≤ s-1
# Q(a,p,m,s) = 1 nếu p trải qua Miller-Rabin cơ sở a
def Q(a, p, m, s):
x = MyMath.powMod(a,m,p)
if x == 1:
return True
for i in range(0,s+1):
if x == p - 1:
return True
x *= x
x %= p
return False
def Miller_Rabin(p, x):
# x : the number of bases
# p - 1 = m*2^s (m is odd)
n = p - 1
s = 0
while n & 1 == 0:
n = n >> 1
s+= 1
m = n
for i in range(x):
a = sprime[i]
if Q(a,p,m,s) == False:
return False
return True
p,q
n = p*q
, φ(n) = (p-1)(q-1)
(e, φ(n)) = 1
def getD(e, phi):
d = MyMath.GCD_extended(e,phi)[0] #[x,y,z] #d = x
if d < 0:
d+= phi
return d
(n, e)
P
UTF-8
tạo thành mảng các số RPi
rồi mã hóa nó thành Ci
với công thức: Ci ≡ Pi^e mod n
def encode(n, e, P, file):
fo = open(file,"w")
C = ""
R = convertStringToInt(P, 4)
A = createBigInt(R, len(str(n)))
for i in A:
M = MyMath.powMod(i,e,n)
M = MyBase.toBase(M,64)
C+= M + ' '
fo.write(M+' ')
fo.close()
return C
cơ số 64
Giải mã
(n, d)
cơ số 10
Ci
giải mã được Pi
với công thức: Pi ≡ Ci^d mod n
def decode(n, d, C, base, fileOut): # file PlanintextDecode
fo = open(fileOut,"w")
P = ""
for i in C:
m = MyMath.powMod(MyBase.toInt(i,64),d,n)
c = str(m)
while len(c) % base != 0:
c = '0' + c
x = 0
while x != len(c):
a = c[x:x+base]
x+= base
P+= chr(int(a))
fo.write(chr(int(a)))
fo.close()
return P
Kiến thức
a^φ(n) ≡ 1 mod n
với (a,n) = 1