본문 바로가기
카테고리 없음

Aes Key Generation Python

by ininscelintaga 2021. 1. 11.


AES Example - Round 1, Substitution Bytes current State Matrix is 0 B B @ 00 3C6E 47 1F 4E 22 74 0E 08 1B 31 54 59 0B1A 1 C C A substitute each entry (byte) of current state matrix by corresponding entry in AES S-Box for instance: byte 6E is substituted by entry of S-Box in row 6 and column E, i.e., by 9F this leads to new State Matrix 0 B B. In PKCS #11 mechanisms refer to the combination of cipher (e.g. AES), hash function (e.g. SHA512) and block mode (e.g. Mechanisms also exist for generating keys, and deriving keys and parameters. The capabilities of a mechanism indicate what types of operations can be carried out with the mechanism, e.g. Encryption, signing, key generation.

Need to encrypt some text with a password or private key in Python? AES-256 is a solid symmetric cipher that is commonly used to encrypt data for oneself. In other words, the same person who is encrypting the data is typically decrypting it as well (think password manager).

Dependencies

For this tutorial, we will be using Python 3, so make sure you install pycryptodome, which will give us access to an implementation of AES-256:

Padding – Handled by GCM

AES-256 typically requires that the data to be encrypted is supplied in 16-byte blocks, and you may have seen that on other sites or tutorials. AES-256 in GCM mode, however, doesn’t require any special padding to be done by us manually.

Encrypting

Now we create a simple encrypt(plain_text, password) function. This function uses the password to encrypt the plain text. Therefore, anyone with access to the encrypted text and the password will be able to decrypt it.

Notes on encrypt() function

  1. Nonce: A random nonce (arbitrary value) must be a random and unique value for each time our encryption function is used with the same key. Think of it as a random salt for a cipher. The library supplies us with a secure nonce.
  2. Scrypt: Scrypt is used to generate a secure private key from the password. This will make it harder for an attacker to brute-force our encryption.
  3. Salt: A new random salt is used for each run of our encryption. This makes it impossible for an attacker to use precomputed hashes in an attempt to crack the cipher. (see rainbow table)
  4. Scrypt parameters:
    1. N is the cost factor. It must be a power of two, and the higher it is the more secure the key, but the more resources it requires to run.
    2. R is the block size.
    3. P is the parallelization factor, useful for running on multiple cores.
  5. Base64: We encode all of our bytes-type data into base64 a convenient string representation
  6. Tag (MAC): The tag is used to authenticate the data when using AES in GCM mode. This ensures no one can change our data without us knowing about it when we decrypt.
Generation

Decrypting

Notes on decrypt() function

  1. The decrypt() function needs the same salt, nonce, and tag that we used for encryption. We used a dictionary for convenience in parsing, but if we instead wanted one string of ciphertext we could have used a scheme like salt.nonce.tag.cipher_text
  2. The configuration parameters on the Scrypt and AES functions need to be the same as the encrypt function.

Give Me The Full Code!

Python 3 aes encryption

You probably want to see it all work in an example script. Look no further!

Thanks For Reading!

Take computer science courses on our new platform

Follow and hit us up on Twitter @q_vault if you have any questions or comments

Subscribe to our Newsletter for more programming articles

Related Reading

When you wish to encrypt and decrypt data in your Python 3 application, you can take a look at pycrypto.

Given that, let us look at how we can encrypt and decrypt data in Python 3 using pycrpto.

Installing pycrypto into your Python 3 environment

In order to use pycrypto, we need to install it.

Therefore, run the following command to install pycrypto into your Python 3 environment:

Getting an instance of the AES to encrypt and decrypt data with the AES encryption algorithm

After you had installed pycrypto in your Python 3 environment, you can then choose an encryption algorithm to encrypt and decrypt your data.

For example, you can write the following Python 3 codes to get an object to encrypt / decrypt data with the AES encryption algorithm:

As shown above, we first import the AES module. After we had done so, we define an encryption key that is 32 bytes long. In case you are wondering, this key must be either 16, 24 or 32 bytes long.

After that, we define an initialization vector that must be 16 bytes long.

Once we have defined the key and initialization vector, we then define a function to get an AES cipher instance.

Whenever we need to perform encryption or decryption, we can use the get_common_cipher function.

Since the cipher object is stateful, we should create a new AES cipher instance whenever we wish to encrypt or decrypt data.

How to encrypt string in Python 3 using pycrypto

When we represent our data as string or text, we can transfer our data easily with HTTP.

Given that, let's look at how we can define a function to encrypt string:

As shown above, we first import the base64 and math modules.

Once we have done so, we define a function encrypt_with_common_cipher that takes a string as an input.

When the function is called, we first get an instance of the AES cipher to perform the encryption.

Since the cipher does not pad our data, we need to do that on our own. Therefore, we first get the length of the text data to compute the next multiple of 16. Once we get the next multiple of 16, we use the rjust method to pad the cleartext with spaces.

Once we had padded our string data to make its size a multiple of 16, we then encrypt it with the AES cipher. When we do so, raw_ciphertext will contain the corresponding cipher text in bytes.

In order to convert the raw_ciphertext to a string, we call base64.b64encode on raw_ciphertext, followed by decode before returning the result to the caller.

How to decrypt string in Python 3 using pycrypto

Whenever we encrypt our string data, there will be a point in time when we want to decrypt it.

Given that, we can define a function to decrypt the cipher text that was created by encrypt_with_common_cipher:

Similar to encrypt_with_common_cipher, we first get an instance of the AES cipher with the same key and initialization vector.

Next, we take the ciphertext, convert it back to bytes and kept it as raw_ciphertext.

Once we get back the cipher text in bytes, we use our AES cipher to decrypt it.

Aes Key Generation Python Commands

When we do so, we will get the decrypted message with padding.

Finally, we decode decrypted_message_with_padding as a string, call strip to remove the spaces and return the result to the caller.

How to encrypt JSON data in Python 3 using pycrypto

At this point in time, encrypting JSON data will be straightforward:

As shown above, we can define a encrypt_json_with_common_cipher function that takes a JSON object as input.

When the function is called, we use json.dumps to convert the JSON object into a JSON string.

Once we have the JSON string, we pass it to the encrypt_with_common_cipher function and return the result back to the caller.

How to decrypt JSON data in Python 3 using pycrypto

When we want to get back the JSON data that we had encrypted, we can define the following function:

As shown above, the decrypt_json_with_common_cipher function takes in a JSON cipher text as an input.

Aes Key Generation Python

Aes Key Generation Python Programming

When the function is called, we call the decrypt_with_common_cipher function to get back the JSON string.

Once we have the JSON string, we use json.loads to get back the JSON object and return it back to the caller.

Putting everything together

In case you want a running example of what was discussed, you can run the following script:

After the function definition for decrypt_json_with_common_cipher, we proceeded to encrypt and decrypt a string and a JSON object.

When you run the script, you should get the following output:

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.

← Previous post
How to create an interval task that runs periodically within your Python 3 Flask application with Flask-APScheduler
Aes Key Generation Python
Next post →
How to use threading.Condition to wait for several Flask-APScheduler one-off jobs to complete execution in your Python 3 application