python RSA中相同密钥的不同解密输出
我正在编写RSA的一个小实现,以帮助我在大学学习,我遇到了一个无法修复的错误 以下是我目前掌握的代码:python RSA中相同密钥的不同解密输出,python,rsa,Python,Rsa,我正在编写RSA的一个小实现,以帮助我在大学学习,我遇到了一个无法修复的错误 以下是我目前掌握的代码: import numpy def primesfrom2to(n): """ Input n>=6, Returns a array of primes, 2 <= p < n Taken from: http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-
import numpy
def primesfrom2to(n):
""" Input n>=6, Returns a array of primes, 2 <= p < n
Taken from: http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """
sieve = numpy.ones(n/3 + (n%6==2), dtype=numpy.bool)
for i in xrange(1,int(n**0.5)/3+1):
if sieve[i]:
k=3*i+1|1
sieve[ k*k/3 ::2*k] = False
sieve[k*(k-2*(i&1)+4)/3::2*k] = False
return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)]
def extended_gcd(a, b):
if b == 0:
return (1, 0)
else:
q = a / b
r = a - b * q
s, t = extended_gcd(b, r)
return (t, s - q * t)
def pick_e(phi):
primes = primesfrom2to(phi)
e = primes[0]
i = 0
while phi % e != 1 and 1 < e < phi:
i += 1
e = primes[i]
return e
def RSA(p, q, e=None):
n = p * q
phi = (p-1) * (q-1)
if not e:
e = pick_e(phi)
x, y = extended_gcd(e, phi)
d = x % phi
return (e, n), (d, n)
def encrypt(P, public_key):
C = P**public_key[0] % public_key[1]
return C
def decrypt(C, private_key):
P = C**private_key[0] % private_key[1]
return P
public_key, private_key = RSA(11, 13)
public_key2, private_key2 = RSA(11, 13, 7)
print public_key, private_key
print public_key2, private_key2
print "public_key and private_key"
print "plaintext -> ciphertext -> plaintext"
for i in range(1,10):
c = encrypt(i, public_key)
p = decrypt(c, private_key)
print "%9d -> %10d -> %9d" % (i, c, p)
print "public_key2 and private_key2"
print "plaintext -> ciphertext -> plaintext"
for i in range(1,10):
c = encrypt(i, public_key2)
p = decrypt(c, private_key2)
print "%9d -> %10d -> %9d" % (i, c, p)
这两个键的输出应该相同,因为键是相同的。有人知道我做错了什么吗?你的pick\u e函数显然返回的是numpy.int64而不是int;如果将return语句替换为
return int(e)
你的代码按预期工作(至少对我来说:-)这不会回答你的问题,但你可以验证你的代码是否正确。这与这个难题有关:(Pdb)
C==128
True(Pdb)(128**103%143)==(C**103%143)
false这是一个numpy.int64而不是一个浮点。这就是我在上面的评论被证明是正确的原因。此外,如果你使用math.pow而不是**,解密将在没有@Frank Schmitt建议的int cast的情况下工作。对此我没有任何解释。感谢您的提示,我已经更正了它(将float替换为numpy.int64)
return int(e)