Search code examples
pythonencryptionmodulecryptography

How to encrypt a variable with the cryptography module?


I'm not sure if any of you are familiar with the cryptography module, but I'm trying to encrypt a variable that stands for a string.

For example:

string = input('String here')

The example they give on the module page is:

from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt(b"A really secret message. Not for prying eyes.")
plain_text = cipher_suite.decrypt(cipher_text)

Which is all fine and dandy, but when I try and replace the "Really secret message string with a variable, It doesn't work.

If it's in quotes, it just prints the name of the variable(duh)

If it's out of quotes like this: cipher_text = cipher_suite.encrypt(bstring), it says variable is not defined(also duh)

But if I just put the variable in, it gives me an error: TypeError: data must be bytes.

Any ideas? Thanks!


Solution

  • According to the Python documentation,

    bytes and bytearray objects are sequences of integers (between 0 and 255), representing the ASCII value of single bytes

    I think the input needs to be like so

    a = b"abc"
    

    (Note the "b").

    An alternate way of achieving this is

    a = bytes("abc")