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 secrets
from string import ascii_letters
from string import digits
def generate_random_symmetric_key():
alphabets_digits = ascii_letters + digits
encrypted_key = ''.join(secrets.choice(alphabets_digits) for i in range(10))
return encrypted_key
print(generate_random_symmetric_key())

Code explanation

  • Line 1: We import the secrets module, which is utilized to generate random numbers with a high level of cryptographic strength.
  • Line 2: We import ascii_letters from the string library, which contains a constant string with both lowercase and uppercase letters, i.e., “a” to “z” and “A” to “Z.”
  • Line 3 We import digits from the string library, 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_letters and digits string.
  • Line 7: We generate a random string containing 10 characters by choosing characters randomly from alphabets_digits using secrets.choice(). The resulting string is stored in encrypted_key variable.
  • Line 8: We return the encrypted_key variable.
  • Line 10: We print the returned value.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved