DEV Community

Sheary Tan
Sheary Tan

Posted on

4 2

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️