gpt4 book ai didi

python - 使用 RSA 加密

转载 作者:行者123 更新时间:2023-12-01 08:37:09 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com