简体   繁体   English

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

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

I've been trying to encrypt data in Python with RSA in pycrypto.我一直在尝试使用 pycrypto 中的 RSA 加密 Python 中的数据。 I've tried to follow the instructions here: http://www.laurentluce.com/posts/python-and-cryptography-with-pycrypto/ but here's what comes out when I call enc_data = public_key.encrypt('abcdefgh', 32) :我尝试按照此处的说明进行操作: 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'

Thanks in advance for any advice regarding this issue.在此先感谢您提供有关此问题的任何建议。

If you look at the encrypt method:如果您查看encrypt方法:

plaintext (byte string or long) - The piece of data to encrypt with RSA. plaintext (字节串或长) - 用 RSA 加密的数据块。 It may not be numerically larger than the RSA module (n).它在数值上不能大于 RSA 模块 (n)。

Your data is not a byte string or long.您的数据不是字节字符串或长字符串。 If you want to input text then you first need to use a character encoding such as UTF-8 for input.如果要输入文本,则首先需要使用字符编码(例如 UTF-8)进行输入。

Note that "plaintext" is just the input for the cryptographic primitives.请注意,“纯文本”只是加密原语的输入。 All modern ciphers operate on bytes.所有现代密码都对字节进行操作。 Historically the input may have been actual text, but not anymore.从历史上看,输入可能是实际的文本,但现在不是了。


Also note that:另请注意:

Attention: this function performs the plain, primitive RSA encryption (textbook).注意:该函数执行普通的、原始的 RSA 加密(教科书)。 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.建议改用模块Crypto.Cipher.PKCS1_OAEPCrypto.Cipher.PKCS1_v1_5

For these functions it is also required to convert your text to byte arrays.对于这些函数,还需要将文本转换为字节数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM