python - 使用 RSA 加密

标签 python encryption cryptography rsa public-key-encryption

我正在尝试编写自己的 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?

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

最佳答案

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

c = m^e mod n

您需要将 n 添加到 pow 调用的末尾:

encrypted = pow(encoded, e, n)

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

plaintext = pow(encrypted, d, n)

关于python - 使用 RSA 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53659953/

相关文章:

python - 谷歌应用引擎 (Python) : use UserProperty with Webapp2 User Model

security - 专门构建的轻量级替代 SSL/TLS?

c - 长文件的RSA加密/解密

c# - 在 .NET 中解密和检查签名时如何忽略系统存储?

python - Beautifulsoup 中的 find 函数在第一个列表中返回 None

python - 元组是不可变的,在替换其条目之前创建列表

encryption - 使用 OpenSSL 进行 Tar 和加密,并将结果直接转储到 ssh 服务器

php - 凯撒密码未按预期运行

c++ - 分析 C++ rand()

python - Centos - 没有名为 yum 的模块