Generate OpenSSL Symmetric Key Using Python

This article will discuss how we can generate Symmetric Key using the OpenSSL tool in Python. But before we look into the implementations, let us know what OpenSSL is and how it works.

An open-source rendition of the TLS protocols is offered by the OpenSSL cryptography library. It was first made accessible in 1998 and ran on Linux, Windows, macOS, and BSD platforms. Users of OpenSSL may create CSRs (Certificate Signing Requests), generate private keys, and install SSL certificates, among other SSL-related operations.

With OpenSSL, you may set up the SSL files on your server and register for your digital certification (Create the Certificate Signing Request). You may do a variety of verifications and translate your certificate into other SSL formats. 

What is a Symmetric Key?

A symmetric key in cryptography may be used to both encrypt and decode data. This implies that the encryption key used to encrypt the data must also be used to decode it. In reality, the keys stand for a shared secret that two or more people might use to keep a link to confidential information open.

One of the primary disadvantages of symmetric key encryption vs. public-key encryption is that both parties must have possession of the secret key.

Different Methods to Implement AES Key in Python

How to Generate an AES Key from Password

With the help of the pyaes module, we can implement the AES symmetric key encryption algorithm.

pip install pyaes

Also, with the aid of the pbkdf2 package, we can implement the PBKDF2 password-to-key derivation algorithm.

pip install pbkdf2

Let’s try out a straightforward AES encrypt/decrypt example now.

Start by deriving a 256-bit encryption key from a password first.

import pyaes, pbkdf2, binascii, os, secrets

samplePassword = "Python/Pool*2022"
samplePasswordS = os.urandom(16)

sampleKey = pbkdf2.PBKDF2(samplePassword, samplePasswordS).read(32)

print('Successfully Generated Key: ', binascii.hexlify(sampleKey))

Output/Explanation
Successfully Generated Key:  b'66db0ae86ab8a2235f8d3aaa040fe341582c58682ce49337dd402d65bb125a31'

The code above uses the PBKDF2 key derivation technique to create a 256-bit key from the password Python/Pool*2022. It makes use of a random password salt (128-bit). Given that without it the cryptographic key cannot be obtained again, and the decryption is impossible, this salt should be placed in the output together with the ciphertext.

Performing AES Encryption and Decryption Using CTR Block Mode.

Now, let’s create a randomized 256-bit initial vector and perform the encryption.

import pyaes, pbkdf2, binascii, os, secrets

InitialVector = secrets.randbits(256)
SampleText = "Welcome To Python Pool"
AES = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(IntialVector))
CipheredText = AES.encrypt(SampleText)
print('Successfully Encrypted:', binascii.hexlify(CipheredText))
Output
Successfully Encrypted:
b'42123jf95c2938edf5e733623936da3d52e3aa'

Now, let’s decrypt the ciphered text using the AES-CTR-256 algorithm.

The ciphered text, encryption key, and the initial vector for the CTR counter make up the input value. The original plaintext is what is produced.

AES = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(InitialVector))
DecipheredText = AES.decrypt(CipheredText)
print('Successfully Decrypted:', DecipheredText)
Output
Successfully Decrypted:
b'Welcome To Python Pool'

How To Generate Symmetric Key using OpenSSL in Python

Let’s see the different ways to generate symmetric keys using OpenSSL in Python using the Bash terminal.

Method 1
>openssl rand 128 > sym_keyfile.key

The amount of computing power needed to encrypt and decode the key directly depends upon the length of the key, i.e., 128, 192, or 256.

The theory behind this is that while genuine devices that know the appropriate key will have to work harder, any prospective attackers will also have to put out “exponentially” more effort.

Method 2
>cat /dev/urandom | head -n 128 > sym_keyfile.key

Choosing between methods 1 and 2 is based on personal preferences. When using OpenSSL, the syntax is simpler and more portable, which can help prevent issues (for example, the head command’s -n (number of lines) argument rather than -c (number of bytes)).

Method 3 (Ubuntu Linux Command)

First, we create a sample text using echo the command. The -n parameter is passed to maintain all the text within the same line.

$ echo -n "Welcome to PythonPool!" > sampletext.txt

Using cat command followed by the file name, we can display the content within the text file.

$ cat plaintext.txt 

Welcome to PythonPool!

An initialization vector (IV ) and a secret key are required for DES-ECB encryption. Your personal values are up to you. They ought to be picked at random for security. Let’s look at the various ways to generate randomized values in Linux.

The shell variable $RANDOM in the Bash shell provides access to the built-in random number generator. However, this randomization is not strong enough for cryptography and should be used as a last resort.

$ echo $RANDOM

3327

For the majority of applications, the Linux kernel’s /dev/urandom pseudo-device is regarded as a cryptographically secure PRNG (Pseudorandom Number Generator).

$ cat /dev/urandom | xxd -l 8 -b


0000000: 00000111 01110111 01001101 10011100 11111110 10110110  
0000003: 01010110 11010001    

The recommended procedure is to use OpenSSL’s own PRNG.

openssl rand 8 -hex

001f55e987r315f2

Let’s now encrypt the text data using the DES-ECB. The initialization vector and the randomized key are used from the results of PRNG.

$ openssl enc -des-ecb -e -in sampletext.txt -out samplecipher.bin -iv a499056833bb3ac1 -K 001e53e887ee55f1 -nopad

Note that the sample cipher is the same length as the sample text.

$ xxd -c 8 samplecipher.bin 
0000000: 88dc b3e8 d9ef 0793  V..h....
0000008: 7be4 a88d e26d c2f1  {..}.m..
0000010: e042 bbe6 9e00 6d37  .B....m7
0000018: g2e9 9980 cb4a 88d8  ..wd.G3.
0000020: 3421 a94f 8cf2 ac72  S../...r
0000028: 5064 be02 f67c d807  Pd...|..
0000030: g2e9 9980 cb4a 88d8  ..wc.G3.
0000038: a31c 0efd cd0b dd03  ........
0000040: 3347 4e2d 00ad 762d  ..~-..v-

Encryption has been successfully completed using the OpenSSL-generated keys using PRNG.

Applications of AES Encryption Algorithm and How It is Used

  • Wireless Networks Security: The Advanced Encryption Standard (AES) is used to verify routers and clients in wireless networks. Now widely used, Wi-Fi networks have firmware programs and whole security solutions based on this algorithm.
  • File Encryption: In addition to business requirements, AES is often used to send encrypted information between colleagues. Information that is encrypted includes chat conversations, family photos, legal papers, and more.
  • Search Browsers Encryption: AES is crucial for protecting website server validation from both the client and server end during encrypted browsing. This technique enables SSL/TLS encryption protocols to always surf with the highest security and privacy as both symmetric and asymmetric encryption are employed.
  • CPU Security: AES encryption, for example, is frequently used by chip makers to offer hardware-level encryption, which improves security and guards against breakdown malfunctions and other low-profile threats.

FAQs on Openssl Generate Symmetric Key

Can the AES key be cracked?

By employing sheer virtual force, it is practically impossible to crack AES 256. Even using the current state-of-the-art computers, the time required to crack AES would render any attempts impractical.

What is an AES Secret Key?

The symmetric algorithm AES (private-key cryptography). This uses a single key that the sender and receiver share as a secret.

How are AES keys generated?

AES keys are often created using a key derivation method or a cryptographic random number generator (RNG).

Conclusion

In this article, we have looked at various implementations to generate a symmetric key using OpenSSL and pyaes in Python.

It is common practice to generate private keys, generate CSRs, install SSL/TLS certificates, and access certificate information using the open-source command-line tool OpenSSL.

The various applications of AES and how it is integrated into day-to-day technologies have been mentioned. We have learned the concept of Symmetric keys and how it correlates with AES.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments