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

I've been trying to encrypt data in Python with RSA in pycrypto. 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):

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.

Answers


If you look at the encrypt method:

plaintext (byte string or long) - The piece of data to encrypt with RSA. It may not be numerically larger than the RSA module (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.

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). 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.

For these functions it is also required to convert your text to byte arrays.


Need Your Help