-1

I'm new to cryptography and I want to learn how can I encrypt and decrypt messages. For example my message is this: "1234, abcd, '123CE'" will I be able to encrypt this message at once? I tried this:

encryption_key = Fernet.generate_key()
fernet = Fernet(encryption_key)
encrypt_message = fernet.encrypt(message.encode())

but i get the error TypeError: can only concatenate str (not "bytes") to str

any help is appreciated, thanks.(i'm using python3 by the way)

opia
  • 65
  • 1
  • 7
  • `encrypt_message = fernet.encrypt(message)`? Possible duplicate of https://stackoverflow.com/questions/55033372/can-only-concatenate-str-not-bytes-to-str. – CristiFati Apr 08 '21 at 08:38
  • Not reproducible. Why do you describe the content of `message` in text instead of posting an _executable_ code? – Topaco Apr 08 '21 at 09:10
  • as i said, i'm trying to learn how to do such an encryption :) first thing comes up to my mind was that code piece – opia Apr 08 '21 at 09:33

1 Answers1

0

The following code works for me :

Python 3.8.3 (default, May 19 2020, 06:50:17) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cryptography.fernet as cpf
>>> key = cpf.Fernet.generate_key()
>>> f = cpf.Fernet(key)
>>> m = f.encrypt("1234, abcd, '123CE'".encode())
>>> m
b'gAAAAABgbsGYBZjqDDilTYl5zmBfENlPkEbEdnK242_K1IBovuL-oiGrvvZmUZZMUoMQ2jYUdJ32GaI834U_Oe5Bdxhf6r-hIG5KwFawfmN45ewjSlgmzx4='

However, you problem can happen when generating your strings:

>>> s = "my string" + b"my bytestring"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "bytes") to str
>>> s = "my string" + b"my bytestring".decode()
>>> s
'my stringmy bytestring'

Make sure you convert all you strings to either str or bytestring format before trying to concatenate them. For that, use :

  • s.decode() to convert s to str if s is a bytestring
  • s.encode() to convert s to bytestring if s is of str type.
SpaceBurger
  • 537
  • 2
  • 12