【问题标题】:Python RSA encryption errorsPython RSA 加密错误
【发布时间】:2017-06-20 23:05:15
【问题描述】:

我正在尝试在 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)

【问题讨论】:

  • pow(encrypted, pubkeyexponent, totient)pow(networkmessage, prikeyexponent, totient) 使用了错误的模数。在这些行中将totient 替换为modulus
  • 迟到总比不到好 - 谢谢!

标签: python python-3.x encryption rsa


【解决方案1】:

你可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-03
    • 2011-02-24
    • 1970-01-01
    • 2018-10-27
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    相关资源
    最近更新 更多