首页 > 解决方案 > 使用 RSA 加密

问题描述

我正在尝试编写自己的 RSA 实现,但遇到了一些麻烦。

我有分别包含 (n, e) 和 (n, d) 的私钥和公钥,但我不确定如何使用它们进行加密。我已经将我希望加密的明文编码为一个非常大的整数 - 在加密的情况下是否就像将该数字提高 e 一样简单?我对此表示怀疑,因为我没有在任何地方使用 n 尽管我确定我需要这样做。

这是我的代码:

def encrypt(self, plaintext_file, encrypted_file):
    with open(plaintext_file, 'rb') as fin:
        plaintext_bin = fin.read()
        plaintext = plaintext_bin.decode('utf-8')

    with open("public.txt", "r") as fin:
        lines = fin.readlines()
        n, e = int(lines[0].strip()), int(lines[1].strip())

    alphabet = ".,?! \t\n\rabcdefcdghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    encoded = self.to_base10(plaintext, alphabet)
    encrypted = pow(encoded, e)  # is this right?

我也很好奇如何解密以验证它是否正常工作。

标签: pythonencryptioncryptographyrsapublic-key-encryption

解决方案


RSA的Wikipedia页面包含精确的加密算法。

c = m^e mod n

您需要在通话n结束时添加:pow

encrypted = pow(encoded, e, n)

然后,您可以通过以下方式解密:

plaintext = pow(encrypted, d, n)

推荐阅读