generate_symmetric_key

generate_symmetric_key

Functions

Name Description
generate_symmetric_key Generate a cryptographically secure random key for symmetric encryption.

generate_symmetric_key

generate_symmetric_key.generate_symmetric_key(filepath=None)

Generate a cryptographically secure random key for symmetric encryption.

This function creates a URL-safe base64-encoded key that can be used with symmetric encryption algorithms. The key is generated using secure random number generation to ensure cryptographic strength.

Parameters

Name Type Description Default
filepath (str, optional(default=None)) Filepath to save the generated key. If no filepath is specified, the key will not be saved to a file. None

Returns

Name Type Description
str A base64-encoded string representing the encryption key. This key should be kept secret and used for both encryption and decryption.

Raises

Name Type Description
ValueError If the provided filepath is invalid or contains illegal characters.

Notes

The function generates a 256-bit (32-byte) key suitable for AES-256 encryption. The key is cryptographically secure and uses the Crypto.Random module which provides access to a cryptographically strong random number generator.

If a filepath is provided, the function will create any necessary parent directories and save the key to the specified file.

Security Best Practices:

  • Never commit keys to version control (add key files to .gitignore)
  • Store keys securely using environment variables or secure key management systems
  • Restrict file permissions when saving keys to disk (chmod 600 on Unix systems)
  • Use the same key for both encryption and decryption operations
  • Keep keys confidential - anyone with the key can decrypt your messages

See Also

encrypt_symmetric : Encrypt messages using the generated key decrypt_symmetric : Decrypt messages using the generated key

Examples

>>> key = generate_symmetric_key()
>>> isinstance(key, str)
True
>>> len(key) > 0
True
>>> # Generate multiple keys - each should be unique
>>> key1 = generate_symmetric_key()
>>> key2 = generate_symmetric_key()
>>> key1 != key2
True
>>> # Practical usage: Generate and store a key
>>> encryption_key = generate_symmetric_key()
>>> # Store this key securely - it will be needed for both encryption and decryption
>>> print(f"Generated key: {encryption_key[:10]}...")
Generated key: aB3dEf7gH9...
>>> # Save key to file (remember to add to .gitignore!)
>>> key = generate_symmetric_key("path/to/key.txt")
>>> # Recommended: Use environment variables instead of files
>>> import os
>>> key = generate_symmetric_key()
>>> os.environ['ENCRYPTION_KEY'] = key