generate_key

static EncryptHelper.generate_key(output: Optional[Union[str, _io.TextIOWrapper]] = None, mode='w')str[source]

Generate a compatible encryption key for use with cryptography.fernet.Fernet

NOTE: Regardless of whether or not the method is outputting the key to a filename / stream, this method will always return the encryption key as a string after completion. The key returning was redacted from the outputting examples to help readability.

Examples

With no arguments, it will simply return the key as a string.

>>> EncryptHelper.generate_key()
'6vJ_o8XQRmX_TgUFTWWV_U2vm71ThnpWsCIvgXFWg9s='

If output is a str - it’s assumed to be a filename, and the Fernet key will be outputted to the file output using open(output, mode) (where mode defaults to 'w').

Below, we call generate_key with the string test.key.txt - and we can then see the file was created and contains the Fernet key encoded with Base64.

>>> EncryptHelper.generate_key('test.key.txt')
>>> open('test.key.txt').read()
'aRDR-gCrmrPrMr9hQnL4epIPl2Szbzfid_vSTO-rl20='

If output is a file/stream object, the method output.write(key) will be called, where key is the Fernet key as a string.

Below, we open test2.key.txt in write mode manually, then pass the file stream object to generate_key, which writes the key to the file.

>>> with open('test2.key.txt', 'w') as fp:
...     EncryptHelper.generate_key(fp)
>>> open('test2.key.txt').read()
'DAFEvRkwG7ws0ccjIv2QL_s5cpeWktqpbc7eSjL-V74='
Parameters
  • output (TextIOWrapper) – Simply return the generated key

  • output – Output the generated key to the filename output using the open mode mode

  • output – Output the generated key to the file/stream object output using .write(key: str)

  • mode (str) – If you’re passing a string filename as output - then this controls the open() mode, e.g. ‘w’, ‘a’, ‘w+’

Return str key

The generated Fernet key, encoded with Base64.