introduction to cryptography; demo 1

in #encrypt2 years ago (edited)

This first demo reproduces the minimal example from https://cryptography.io/en/latest/fernet/

Here is the code:

      from cryptography.fernet import Fernet

      key = Fernet.generate_key()
      f = Fernet(key)
      token = f.encrypt(b"A really secret message. Not for prying eyes.")

Running this code snippet generates the key "key=Fernet.generate_key()" that is used to encrypt the message "A really secret message. Not for prying eyes".

The token is the encrypted message:
      token = str.encode('gAAAAABkA82hbypi9ImmSnP_MGiqkuAHY-8fSsBdnl4qd2or6cQF_6stRh2RDHEvNGkuxQ9sc4nC0HKl9_f1Ax5LOPNaWFJUOjVgWt5ix0EzdcfrJJxslBd3f2GyOPOawJmdHDRwTO4N', 'utf-8')

Try decoding it with this key:
      key = str.encode('LB83JBWFeETaE7NoBgJme0tOBDbV65lLa1H23YDQ6M0=', 'utf-8')

Did you notice the lowercase b used for the message and the key? The lowercase b tells Python that the data is coded in binary (1s and 0s).

Fernet is a symmetric encryption algorithm. This means that the same key is used to encrypt and decrypt the message.

Python snippet to decode the message:

New variable names are used so that we don't over-write the values of the variables already defined (key, token, f):

      key2 = str.encode('LB83JBWFeETaE7NoBgJme0tOBDbV65lLa1H23YDQ6M0=', 'utf-8')
      token2 = str.encode('gAAAAABkA82hbypi9ImmSnP_MGiqkuAHY-8fSsBdnl4qd2or6cQF_6stRh2RDHEvNGkuxQ9sc4nC0HKl9_f1Ax5LOPNaWFJUOjVgWt5ix0EzdcfrJJxslBd3f2GyOPOawJmdHDRwTO4N', 'utf-8')

      f2 = Fernet(key2)
      message = f2.decrypt(token2)
      print(message)

Output:
      b'A really secret message. Not for prying eyes.'


I am new to Steemit, please let me know if you have any questions, comments, or constructive criticisms. Thanks!