Generate Random Aes Key Python

  1. Generate Aes Key Python

If you want the user to enter a password, don't limit the length (except maybe to set a minimum), and use something like PBKDF2 to stretch the key and slow down dictionary guesses against the password. (As @marstato commented). On the other hand, if you want to generate a random key, pull bytes out a strong random bit generator, and save it in. The following are code examples for showing how to use Crypto.Cipher.AES.keysize.They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

an example of symmetric encryption in python using a single known secret key - utilizes AES from PyCrypto library

The following are code examples for showing how to use Crypto.Random.getrandombytes.They are from open source Python projects. You can vote up the examples you like.

# Inspired from
# PyCrypto docs available at
importbase64, os
# AES key length must be either 16, 24, or 32 bytes long
AES_key_length=16# use larger value in production
# generate a random secret key with the decided key length
# this secret key will be used to create AES cipher for encryption/decryption
# encode this secret key for storing safely in database
defencrypt_message(private_msg, encoded_secret_key, padding_character):
# decode the encoded secret key
# use the decoded secret key to create a AES cipher
# pad the private_msg
# because AES encryption requires the length of the msg to be a multiple of 16
padded_private_msg=private_msg+ (padding_character* ((16-len(private_msg)) %16))
# use the cipher to encrypt the padded message
# encode the encrypted msg for storing safely in the database
# return encoded encrypted message
defdecrypt_message(encoded_encrypted_msg, encoded_secret_key, padding_character):
# decode the encoded encrypted message and encoded secret key
# use the decoded secret key to create a AES cipher
# use the cipher to decrypt the encrypted message
# unpad the encrypted message
# return a decrypted original private message
####### BEGIN HERE #######
Lorem ipsum dolor sit amet, malis recteque posidonium ea sit, te vis meliore verterem. Duis movet comprehensam eam ex, te mea possim luptatum gloriatur. Modus summo epicuri eu nec. Ex placerat complectitur eos.
encrypted_msg=encrypt_message(private_msg, secret_key, padding_character)
decrypted_msg=decrypt_message(encrypted_msg, secret_key, padding_character)
print' Secret Key: %s - (%d)'% (secret_key, len(secret_key))
print'Encrypted Msg: %s - (%d)'% (encrypted_msg, len(encrypted_msg))
print'Decrypted Msg: %s - (%d)'% (decrypted_msg, len(decrypted_msg))

commented Jan 18, 2019

See also for an example using cryptography

Generate Aes Key Python

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment