How to generate random AWS-like access key / secret key in Python
Typically, AWS access keys have a length of 20 characters from the following set: ABCDEFGHIJKLMNOPQRSTUVWXYZ234567
(also called uppercase base32
encoding)
The following Python code can be used to generate random AWS-like access keys & secret keys:
import base64
import secrets
def generate_random_base32_key(length=20):
"""
Generate a random uppercase base32 string of the given length.
"""
bytes_length = (length * 5) // 8
random_bytes = secrets.token_bytes(bytes_length)
base32_string = base64.b32encode(random_bytes).decode()[:length]
return base32_string.upper()
# Usage example
random_access_key = generate_random_base32_key(20)
print(random_access_key)
Example output:
IBVCAVULO2CQTOQEE6VQ
5ONXKHGNV3ILTX3BGJGA
2B4QYQ2RFGWK2LSON4YQ
VO5APZH2B2KS75GWORFQ
SXCBFBDXLUNCJMCFM2SQ