DEV Community

Sheary Tan
Sheary Tan

Posted on

Data Decryption and Encryption using AES

In this post we are going to do a basic data encryption and decryption using OpenSSL.

To encrypt the data

First, lets create a plain text file with a simple text in it

$ echo TextDataToEncrypt > message.txt
Enter fullscreen mode Exit fullscreen mode

And we have successfully generated a text file!

Next we are using 256-bit AES in CBC mode to encrypt the file:

$ openssl enc -aes-256-cbc -in message.txt -out message.bin
Enter fullscreen mode Exit fullscreen mode

It will then ask you to enter your password for the encryption:

enter aes-256-cbc encryption password:
Verifying - enter aes-256-cbc encryption password:
Enter fullscreen mode Exit fullscreen mode

After that a file message.bin containing the encrypted data from the message.txt file will be generated.

We can view this file:

$ cat message.bin
Enter fullscreen mode Exit fullscreen mode

It is desirable to encode the binary file in a text format for compatibility/interoperability reasons.
A common one is base64.
This is how to create base64-encoded message:

$ openssl enc -base64 -in message.bin -out message.b64
Enter fullscreen mode Exit fullscreen mode

We can then view the file:

$ cat message.b64
U2FsdGVkX1/Xe/SswefSAEA6z3cykrRZOFEFwIvREwQTY=
Enter fullscreen mode Exit fullscreen mode

To decrypt the data

Here we are decrypting text data from message.bin:

$ openssl enc -d -aes-256-cbc -in message.bin -out message.dec
Enter fullscreen mode Exit fullscreen mode

It will ask you to enter the password you've entered before:

enter aes-256-cbc decryption password:
Enter fullscreen mode Exit fullscreen mode

It will then generate a decrypted file (message.dec). We can view the decrypted text by running the command:

$ cat message.dec
TextDataToEncrypt
Enter fullscreen mode Exit fullscreen mode

And that's it!

Source: Mastering Blockchain. I don't own any of these information, I am just sharing.

Top comments (0)