How to generate a random symmetric encryption key in Python
Random symmetric encryption keys are commonly used in various cryptographic algorithms and protocols for secure communication and data protection. The following are just a few of examples of where they are used:
- Database encryption
- Secure communication
- Password storage
Code example
To generate a random symmetric encryption key, a coding example in Python is given below:
import secretsfrom string import ascii_lettersfrom string import digitsdef generate_random_symmetric_key():alphabets_digits = ascii_letters + digitsencrypted_key = ''.join(secrets.choice(alphabets_digits) for i in range(10))return encrypted_keyprint(generate_random_symmetric_key())
Code explanation
- Line 1: We import the
secretsmodule, which is utilized to generate random numbers with a high level of cryptographic strength. - Line 2: We import
ascii_lettersfrom thestringlibrary, which contains a constantstringwith both lowercase and uppercase letters, i.e., “a” to “z” and “A” to “Z.” - Line 3 We import
digitsfrom thestringlibrary, which contains a constant string with digits from “0” to “9.” - Line 5: We declare the function named
generate_random_symmetric_key. - Line 6: We concatenate the
ascii_lettersanddigitsstring. - Line 7: We generate a random string containing 10 characters by choosing characters randomly from
alphabets_digitsusingsecrets.choice(). The resulting string is stored inencrypted_keyvariable. - Line 8: We return the
encrypted_keyvariable. - Line 10: We print the returned value.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved