【发布时间】:2019-10-12 12:42:22
【问题描述】:
我正在尝试实施 RSA。但我有一些问题。我正在尝试用 2 个素数加密一个字符串。
p= 1606938044258990275541962092341162602522202993782792835301611
q= 3213876088517980551083924184682325205044405987565585670603103
首先我为 RSA 算法做必须做的事情。加密字符串后,我也尝试解密它。但结果是这样的:ÜŞϟʐͶz̽ć
def xgcd(a, b):
"""return (g, x, y) such that a*x + b*y = g = gcd(a, b)"""
x0, x1, y0, y1 = 0, 1, 1, 0
while a != 0:
q, b, a = b // a, a, b % a
y0, y1 = y1, y0 - q * y1
x0, x1 = x1, x0 - q * x1
return b, x0, y0
def genKeypair(p, q):
n = p * q
phiN = (p - 1) * (q - 1)
e = 65537
d = egcd(phiN, e)
return n, e, d
# encrypt message and return cipher
def encrypt(m, n, e):
m1 = ""
# Turn message string into ascii so it can be used for encryption
for x in range(len(m)):
m1 += '{0:03}'.format(ord(m[x]))
# encrypt
c = squareAndMultiply(int(m1), e, n)
print(c)
return c
# decrypt cipher and return message
def decrypt(c, n, d):
# decrypt c
m = squareAndMultiply(c, d, n) #% n
# put decryption result into ascii format and use ascii to decode it
m = str(m)
tmp = ""
message = ""
i = 0
if int(m[0] + m[1] + m[3]) > 255:
m = "0" + m
for x in range(len(m)):
tmp = tmp + m[x]
i += 1
if i % 3 == 0:
message += chr(int(tmp))
tmp = ""
return message
我的平方和乘法如下所示:
def squareAndMultiply(x, n, m=0):
# turn exponent into binary
bin = '{0:b}'.format(n)
r = x
# loop through the string representing the binary form of the exponent while ignoring the leftmost bit and perform
# the appropriate operations on r
for i in range(1, len(bin)):
if (bin[i] == "0"):
r *= r % m
else:
r *= r % m
r *= x % m
# check for m being greater than 0, ignore it otherwise
if (m > 0):
return r % m
else:
return r
有没有人知道什么可能是错的,什么必须改变,解密给出正确的答案?
【问题讨论】:
-
您没有使用pow的任何特殊原因?
-
我使用了 pow 并得到了与我自己的实现相同的结果。我需要自己实现平方和乘法。
标签: python encryption rsa