Python 当消息太大时,RSA 编码器不工作

Python RSA encoder doesn't work when message is too large

我正在尝试制作一个 RSA encoder/decoder,它接收消息“m”,将其转换为 ascii 字符串,然后对其进行编码。当我尝试解码该数字时,它给了我一些完全错误的东西。我试过输入少量数字作为消息而不是将其转换为 ascii 并且效果很好。我认为这一定与数字的大小有关。我该如何解决这个问题?

def encode():
    P = int(input("Enter P value (must be prime): "))   #29
    Q = int(input("Enter Q value (must be prime): "))   #41
    n = P * Q                                           #1189
    phiN = (P - 1)*(Q - 1)                              #1120
    e = int(input("Enter e value (1 < e < phiN): "))    #9
    d = pow(e, -1, phiN)                                #249
    print("Your public key is: (n = " + str(n) + ", e = " + str(e) + ")")
    print("Your private key is: (n = " + str(n) + ", d = " + str(d) + ")")
    m = input("Message to encode: ")

    ascii_values = []
    strings = []

    # Converts every character in "m" (message) into ASCII value and append it to
    # ascii_values list
    for character in m:
        ascii_values.append(ord(character))

    # Converts every element in ascii_values list and converts it to a string
    # Appends to "strings" list
    for element in ascii_values:
        strings.append(str(element))

    #Makes all values 3-digits. Dunno if this is really needed
    i = 0
    while i < len(strings):
        while len(strings[i]) != 3:
            strings[i] = "0" + strings[i]
        i += 1

    # Takes "strings" list and joins elements together to make one long string
    a = "".join(strings)
    c = pow(int(a), e, n)
    print("Your encoded message is (" + str(c) + ") Use your private key to decode it")

def decode():
    d = int(input("Enter d value: "))
    n = int(input("Enter n value: "))
    c = int(input("Enter ciphertext (must be integer): "))
    m = pow(c, d, n)
    print("Your decoded message is (" + str(m) + ") Use a decoder to convert to text")

首先你要明白编码和加密的区别。 RSA 是一种非对称加密算法,而不是像 Base64 这样的编码算法。

第二点是,在加密之前将文本像这样转换为数字并不是一个好习惯。如果你想要还有另一种更简单的方法:

m_int = int( 'hello world'.encode().hex() , 16 ) # 126207244316550804821666916

将字符串编码为字节,然后将其转换为十六进制格式,最后转换为数字。 要将其转换回字符串,您应该将其转换为十六进制,然后再转换为字节:

m_string = bytes.fromhex(hex(126207244316550804821666916)[2:]).decode() # 'hello world'

现在在你的例子中你使用RSA 11位密钥,这意味着你的m的最大长度不能超过12位(126207244316550804821666916是88位)才能正确加密和解​​密。 所以你应该通过生成更大的素数来生成更大的密钥。

如果你想制作加密脚本,我建议你查看 pycryptodome 库。