Python RSA加密错误

时间:2017-02-03 14:31:13

标签: python python-3.x encryption rsa

我试图在Python中创建一个简单版本的RSA,但是 - 无论是由于Python整数的限制还是我糟糕的代码 - 它都没有返回与原始相同的解密消息。我的密钥生成器似乎确实创建了有效密钥,所以我很好奇它是如何失败的。

附件是我使用的代码 - 我认为它足够短,不需要添加存根。

from random import randint
from math import sqrt, ceil

#This is the private key the bank uses
bankPrime = 6619319052850372576671203008980947142174030778088896832879139788043990604607
#This is the public key
clientPrime = 89981040860183284202926925086489690550566335265876097787978356913003610730551
#Calculate modulus
modulus = bankPrime * clientPrime

#Calculate totient of modulus
totient = (bankPrime - 1)*(clientPrime - 1)

#Creates random numbers until it passes Euclid's algorithm with the GCD being 1 - coprime generator
def xgcd(b, n):
    x0, x1, y0, y1 = 1, 0, 0, 1
    while n != 0:
        q, b, n = b // n, n, b % n
        x0, x1 = x1, x0 - q * x1
        y0, y1 = y1, y0 - q * y1
    return b, x0

while True:
    pubkeyexponent = randint(3, ceil(sqrt(totient)))
    gcd, prikeyexponent = xgcd(pubkeyexponent, totient)
    if prikeyexponent < 0:
        prikeyexponent += totient
    if gcd == 1:
        break

print("Totient n", totient)
print("Private Key d", prikeyexponent)
print("Public Key e", pubkeyexponent)
print("Modulus", modulus)
print()
print("Type the message you want to encrypt:")
message = input(">:")

encrypted = 0
for x in range(len(message)):
    encrypted += (256**x) * ord(message[x])
print(encrypted)

networkmessage = pow(encrypted, pubkeyexponent, totient)
print("The number message sent over the network to the bank is this:", networkmessage)
encrypted = pow(networkmessage, prikeyexponent, totient)
print("The number message sent back to the client is this:", encrypted)

1 个答案:

答案 0 :(得分:0)

您可以使用 cryptographer

此代码将加密、解密、将 RSA 密钥保存到文件中,然后再次加载它们。

from cryptographer import RSAKey()
key = RSAKey()
encrypted = key.encrypt('Hello World') # also works with bytes data
print('Encrypted Text:', encrypted)
decrypted = key.decrypt(encrypted)
print('Decrypted Text:', decrypted)
# Save key to file
import pickle
pickle.dump(rsa, open('rsa.dat', 'wb')
# Load key from file
old_rsa = rsa
rsa = pickle.load(open('rsa.dat', 'rb'))
print(rsa == old_rsa) # True