如何使用 pycrypto 和 RSA 加密(和解密)数据?

How to encrypt (and decrypt) data with pycrypto and RSA?

我一直在尝试使用 pycrypto 中的 RSA 加密 Python 中的数据。我已尝试按照此处的说明进行操作:http://www.laurentluce.com/posts/python-and-cryptography-with-pycrypto/ 但这是我调用 enc_data = public_key.encrypt('abcdefgh', 32):

时出现的结果
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
  enc_data = public_key.encrypt('abcdefgh', 32)
  File "C:\Python35\lib\site-packages\Crypto\PublicKey\RSA.py", line 150, in encrypt
    return pubkey.pubkey.encrypt(self, plaintext, K)
  File "C:\Python35\lib\site-packages\Crypto\PublicKey\pubkey.py", line 75, in encrypt
    ciphertext=self._encrypt(plaintext, K)
  File "C:\Python35\lib\site-packages\Crypto\PublicKey\RSA.py", line 224, in _encrypt
    return (self.key._encrypt(c),)
  File "C:\Python35\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'

提前感谢有关此问题的任何建议。

如果您查看 encrypt 方法:

plaintext (byte string or long) - The piece of data to encrypt with RSA. It may not be numerically larger than the RSA module (n).

您的数据不是字节串或长数据。如果你想输入文字,那么你首先需要使用UTF-8之类的字符编码进行输入。

请注意,"plaintext" 只是密码原语的输入。所有现代密码都以字节为单位进行运算。从历史上看,输入可能是实际文本,但现在不是了。


另请注意:

Attention: this function performs the plain, primitive RSA encryption (textbook). In real applications, you always need to use proper cryptographic padding, and you should not directly encrypt data with this method. Failure to do so may lead to security vulnerabilities. It is recommended to use modules Crypto.Cipher.PKCS1_OAEP or Crypto.Cipher.PKCS1_v1_5 instead.

对于这些函数,还需要将您的文本转换为字节数组。