65.9K
CodeProject is changing. Read more.
Home

Simple File Encryption using OpenSSL

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.86/5 (3 votes)

Aug 1, 2012

CPOL

2 min read

viewsIcon

23111

downloadIcon

1014

Encrypting/decrypting a file using OpenSSL.

Introduction

This is a simple command line utility to encrypt or decrypt a file using OpenSSL.

Background

Recently, I felt the need to encrypt a file with sensitive information. There are many software available in the market that can do the trick, but I needed simple file encryption in which I would have to do minimal maintenance going forward. For example, if I had used Windows encryption, I would have to follow certain steps if I were to format my computer, or my data will be lost forever. My need was not to encrypt an entire folder, just specific files. In a nutshell, my requirements were as follows:

  • Find a simple utility that does the encrypting. Preferably using commandline, as a GUI is too conspicuous.
  • No installer, as I would not want to install it on different machines that I use (work, home, friend's computer occasionally).
  • In place encryption/decryption and have some safety measures in place, so that the data file does not get overwritten in the process.

Using the code

I found that OpenSSL was just such a utility, which has ability to encrypt/decrypt a file using command line. It is freely available as a 32 bit and a 64 bit download, whichever suits the need. It has many built-in encryption algorithms. I have used AES-256-CBC.

The mechanism is simple:

  • Make a backup of the original Data file.
  • Encrypt/Decrypt the original data file using OpenSSL in an encrypted/decrypted output file.
  • If successful, delete the original data file, and rename the encrypted/decrypted file to the original file name.
  • If unsuccessful, delete any empty encrypted/decrypted file that got created.
  • Finally, delete the backup file.

The EncryptFile.bat and DecryptFile.bat take the filename as the commandline argument.

EncryptFile.bat
ECHO OFF

COPY %1 %1.bak
CLS

openssl aes-256-cbc -in %1 -out %1.enc -e -base64

IF ERRORLEVEL 1 (
    ECHO.
    ECHO ********** UNABLE TO ENCRYPT FILE **********
    DEL %1.enc
    DEL %1.bak
    PAUSE    
) ELSE (
    DEL %1
    REN %1.enc %1
    IF NOT ERRORLEVEL 1 DEL %1.bak
)

ECHO ON
DecryptFile.bat
ECHO OFF

COPY %1 %1.bak
CLS

openssl aes-256-cbc -in %1 -out %1.dec -d -base64

IF ERRORLEVEL 1 (
    ECHO.
    ECHO ********** UNABLE TO DECRYPT FILE **********
    DEL %1.dec
    DEL %1.bak
    PAUSE
) ELSE (
    DEL %1
    REN %1.dec %1
    IF NOT ERRORLEVEL 1 DEL %1.bak
)

ECHO ON

Points of Interest

This is just an abstraction/layer built on top of the OpenSSL tool. Very simple implementation, something I did for myself, but may be you will find it useful too.