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.FernetNOTE: 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
outputis astr- it’s assumed to be a filename, and the Fernet key will be outputted to the fileoutputusingopen(output, mode)(wheremodedefaults to'w').Below, we call
generate_keywith 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
outputis a file/stream object, the methodoutput.write(key)will be called, wherekeyis 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
outputusing the open modemodeoutput – Output the generated key to the file/stream object
outputusing.write(key: str)mode (str) – If you’re passing a string filename as
output- then this controls theopen()mode, e.g. ‘w’, ‘a’, ‘w+’
- Return str key
The generated Fernet key, encoded with Base64.