python - 使用 RSA python 加密消息时出错

标签 python python-3.x encryption rsa

使用示例代码使用 RSA 加密消息,但出现以下错误。

Traceback (most recent call last):
  File "E:/PythonProjects/skypy/skypy/codebase/utils/crypto.py", line 32, in <module>
    print(RSAPubKey.encrypt("Hello.", 32))
  File "E:\Programs\Python3.4\lib\site-packages\Crypto\PublicKey\RSA.py", line 150, in encrypt
    return pubkey.pubkey.encrypt(self, plaintext, K)
  File "E:\Programs\Python3.4\lib\site-packages\Crypto\PublicKey\pubkey.py", line 75, in encrypt
    ciphertext=self._encrypt(plaintext, K)
  File "E:\Programs\Python3.4\lib\site-packages\Crypto\PublicKey\RSA.py", line 224, in _encrypt
    return (self.key._encrypt(c),)
  File "E:\Programs\Python3.4\lib\site-packages\Crypto\PublicKey\_slowmath.py", line 65, in _encrypt
    return pow(m, self.e, self.n)
TypeError: unsupported operand type(s) for pow(): 'str', 'int', 'int'

这里是示例代码

from Crypto.PublicKey import RSA
from Crypto.Util import randpool

blah = randpool.RandomPool()
RSAKey = RSA.generate(1024, blah.get_bytes)

RSAPubKey = RSAKey.publickey()
print(RSAPubKey.encrypt("Hello.", 32))

使用的操作系统是Windows,请问是什么问题导致的?

最佳答案

该错误表明encrypt 方法不支持加密字符串消息。尝试先使用 encode 将字符串编码为字节,例如:

print(RSAPubKey.encrypt("Hello.".encode('utf-8'), 32))

还值得注意的是,根据文档,encrypt 执行“教科书”RSA 加密,由于缺少填充,这是不安全的。您应该改用 Crypto.Cipher.PKCS1_OAEPCrypto.Cipher.PKCS1_v1_5

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

相关文章:

python - 将日期和时间与列表中的日期时间元素分开

python - ast.literal_eval 调用中格式错误的节点

python-3.x - Pygame 不加载图像

javascript - 如何使用 HTML5 <video> 标签播放 CENC 加密的 MP4 视频?

delphi - 在Delphi中加密/解密文本文件?

python - 基于正则表达式/自由文本解析文本文件

python - pop()函数没有完全弹出列表中位数

python - 聚焦时不要设置 Gtk.TreeView 的选择?

python - 多次循环 csv.DictReader 行

java - 如何正确使用 "PBEWithHmacSHA512AndAES_256"算法?