So I've just started experimenting with Pycrypto and wanted to encrypt and decrypt a message, but this code I put together produced some errors.
Here they are:
enc_data = public_key.encrypt
TypeError: unsupported operand type(s) for pow(): 'str', 'int','int'
ciphertext = cipher.encrypt('Bob')
Traceback (most recent call last):
line 22, in ciphertext = cipher.encrypt('Bob')
File "C:\Anaconda3\lib\site-packages\Crypto\Cipher\PKCS1_OAEP.py", line 50, in encrypt
db = lHash + ps + bchr(0x01) + messageTypeError: can't concat bytes to str
The code:
import Crypto
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto import Random
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
public_key = key.publickey()
enc_data = public_key.encrypt('Bob', 32)
cipher = PKCS1_OAEP.new(key)
ciphertext = cipher.encrypt('Bob')
The two commands which are meant to encrypt 'Bob' produce these errors, and yes I now that the first way isn't very secure.
In Python 3 there is a difference between strings and bytes. PyCrypto works on bytes, so you need to give it bytes, but "Bob"
is a string. You can convert a string a
to bytes with a.encode()
, which uses a default encoding. If you have another encoding in mind, then you need to specify it.
You can also mark a literal string as bytes by prefixing it with a b
. Example: b"Bob"
.