python - 使用 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?
我也很好奇如何解密以验证它是否正常工作。
解决方案
RSA的Wikipedia页面包含精确的加密算法。
c = m^e mod n
您需要在通话n
结束时添加:pow
encrypted = pow(encoded, e, n)
然后,您可以通过以下方式解密:
plaintext = pow(encrypted, d, n)
推荐阅读
- python - 将两个不同长度列表的元素相加成一个新列表
- django - django 错误,“精确查找的 QuerySet 值必须限制为使用切片的一个结果”
- groovy - Groovy 注释中的默认数组值
- php - 如何根据数据库中的受控列表值正确管理 Web 应用程序行为?
- django - 获取 Django 查询集中的重复记录
- c++ - 无法使用 FindFirstCHangeNotification 和 FindNextChangeNotification 通知目录更改
- sitecore - 单击sitecore中的发布按钮如何拦截现有的发布窗口?
- c++ - 旋转后如何保持 2D 精灵的纵横比?
- reactjs - 库来处理全局状态以及从 React 中的服务器获取的状态
- github-actions - 下载后 GitHub 操作工件不可用