我正在编写一些代码以使用RSA进行加密。该消息的长度永远不会超过100个字符。 运行代码时,只有部分消息被正确解密。由于将其编码为6个字符块,因此它总是在6个字符的倍数之后中断。 我尝试减少一次编码的字符数,这完全破坏了代码。 我该如何解决? 代码:
from random import randint
from textwrap import wrap
def gcd(a,b):
while True:
if a==0: return b
if b==0: return a
a,b=b,a%b
def eea(e,phi):
x1,y1=phi,phi
x2,y2=e,1
while True:
i=x1//x2
x1,x2=x2,x1-(i*x2)
y1,y2=y2,y1-(i*y2)
x2,y2=x2%phi,y2%phi
if x2==1: return y2
with open("primes.txt","r") as file:
primes=file.read()
primes=primes.split()
primes=list(map(int,primes))
small=[3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541]
def keyPair():
size=len(primes)
p = primes[randint(0,size)]
q = primes[randint(0,size)]
while p==q:
q = primes[randint(0,size)]
n = p * q
phi = (p - 1) * (q - 1)
e = 3
i=1
while gcd(phi,e)!=1:
i+=1
e=small[i]
d = eea(e, phi)
return (e,n),(d,e,n)
def encode(key,plain):
m=""
for x in plain:
m+=str(ord(x)).zfill(3)
print(m)
m=wrap(m,18)
c=""
e=key[0]
n=key[1]
for x in m:
i=str((int(x) ** e) % n)
c+=i
return c
def fast_power(base, power,mod):
result = 1
while power > 0:
if power % 2 == 1:
result = (result * base)%mod
power = power // 2
base = (base * base)%mod
return result
def decode(key,cipher):
c=wrap(cipher,18)
out=""
d=key[0]
n=key[2]
new=[]
for x in c:
x=str(fast_power(int(x),d,n)).zfill(18)
new.append(wrap(x,3))
print(new)
for x in new:
for y in x:
out+=chr(int(y))
return out
pub,priv=(3, 948702900236536321),(632468598859005155, 3, 948702900236536321)
print(pub,priv)
c=encode(pub,"the quick brown fox jumped over the lazy dog. THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.")
m=decode2(priv,c)
print(m)
"""