C++ Code To Encrypt And Decrypt A File Dev C++everxx

Posted on by

Code for Inventory Management System in C Programming. And than encrypt and decrypt. //in to your.exe file so only.exe file is distributed. //For that part. The below code is for a simple password encryption/decryption program. The code is working perfectly, but the only thing I want to know from you is if this is good logic. PEND.h #ifndef PENDH #d.

  • Cryptography with Python Tutorial
  • Useful Resources
  • Selected Reading

Cryptography is the art of communication between two users via coded messages. The science of cryptography emerged with the basic motive of providing security to the confidential messages transferred from one party to another.

Cryptography is defined as the art and science of concealing the message to introduce privacy and secrecy as recognized in information security.

Terminologies of Cryptography

The frequently used terms in cryptography are explained here −

Plain Text

The plain text message is the text which is readable and can be understood by all users. The plain text is the message which undergoes cryptography.

Cipher Text

Cipher text is the message obtained after applying cryptography on plain text.

Encryption

The process of converting plain text to cipher text is called encryption. It is also called as encoding.

Decryption

The process of converting cipher text to plain text is called decryption. It is also termed as decoding.

The diagram given below shows an illustration of the complete process of cryptography −

Characteristics of Modern Cryptography

The basic characteristics of modern cryptography are as follows −

  • It operates on bit sequences.

  • It uses mathematical algorithms for securing the information.

  • It requires parties interested in secure communication channel to achieve privacy.

Double strength encryption, also called as multiple encryption, is the process of encrypting an already encrypted text one or more times, either with the same or different algorithm/pattern.

The other names for double strength encryption include cascade encryption or cascade ciphering.

Levels of Double Strength Encryption

Double strength encryption includes various levels of encryption that are explained here under −

First layer of encryption

The cipher text is generated from the original readable message using hash algorithms and symmetric keys. Later symmetric keys are encrypted with the help of asymmetric keys. The best illustration for this pattern is combining the hash digest of the cipher text into a capsule. The receiver will compute the digest first and later decrypt the text in order to verify that text is not tampered in between.

Second layer of encryption

Second layer of encryption is the process of adding one more layer to cipher text with same or different algorithm. Usually, a 32-bit character long symmetric password is used for the same.

Third layer of encryption

In this process, the encrypted capsule is transmitted via SSL/TLS connection to the communication partner.

The following diagram shows double encryption process pictorially −

Hybrid Cryptography

Hybrid cryptography is the process of using multiple ciphers of different types together by including benefits of each of the cipher. There is one common approach which is usually followed to generate a random secret key for a symmetric cipher and then encrypt this key via asymmetric key cryptography.

Due to this pattern, the original message itself is encrypted using the symmetric cipher and then using secret key. The receiver after receiving the message decrypts the message using secret key first, using his/her own private key and then uses the specified key to decrypt the message.

Python is an open source scripting language which is high-level, interpreted, interactive and object-oriented. It is designed to be highly readable. The syntax of Python language is easy to understand and uses English keywords frequently.

Features of Python Language

Python provides the following major features −

Interpreted

Python is processed at runtime using the interpreter. There is no need to compile a program before execution. It is similar to PERL and PHP.

Object-Oriented

Python follows object-oriented style and design patterns. It includes class definition with various features like encapsulation and polymorphism.

Key Points of Python Language

The key points of Python programming language are as follows −

  • It includes functional and structured programming and methods as well as object oriented programming methods.

  • It can be used as a scripting language or as a programming language.

  • It includes automatic garbage collection.

  • It includes high-level dynamic data types and supports various dynamic type checking.

  • Python includes a feature of integration with C, C++ and languages like Java.

The download link for Python language is as follows − www.python.org/downloadsIt includes packages for various operating systems like Windows, MacOS and Linux distributions.

Python Strings

The basic declaration of strings is shown below −

Python Lists

The lists of python can be declared as compound data types, separated by commas and enclosed within square brackets ([]).

Python Tuples

A tuple is dynamic data type of Python which consists of number of values separated by commas. Tuples are enclosed with parentheses.

Python Dictionary

Python dictionary is a type of hash table. A dictionary key can be almost any data type of Python, which are usually numbers or strings.

Cryptography Packages

Python includes a package called cryptography which provides cryptographic recipes and primitives. It supports Python 2.7, Python 3.4+, and PyPy 5.3+. The basic installation of cryptography package is achieved through following command −

There are various packages with both high level recipes and low level interfaces to common cryptographic algorithms such as symmetric ciphers, message digests and key derivation functions.

Throughout this tutorial, we will be using various packages of Python for implementation of cryptographic algorithms.

The previous chapter gave you an overview of installation of Python on your local computer. In this chapter you will learn in detail about reverse cipher and its coding.

Algorithm of Reverse Cipher

The algorithm of reverse cipher holds the following features −

  • Reverse Cipher uses a pattern of reversing the string of plain text to convert as cipher text.

  • The process of encryption and decryption is same.

  • To decrypt cipher text, the user simply needs to reverse the cipher text to get the plain text.

Drawback

The major drawback of reverse cipher is that it is very weak. A hacker can easily break the cipher text to get the original message. Hence, reverse cipher is not considered as good option to maintain secure communication channel,.

Example

Consider an example where the statement This is program to explain reverse cipher is to be implemented with reverse cipher algorithm. The following python code uses the algorithm to obtain the output.

Output

You can see the reversed text, that is the output as shown in the following image −

Explanation

  • Plain text is stored in the variable message and the translated variable is used to store the cipher text created.

  • The length of plain text is calculated using for loop and with help of index number. The characters are stored in cipher text variable translated which is printed in the last line.

In the last chapter, we have dealt with reverse cipher. This chapter talks about Caesar cipher in detail.

Algorithm of Caesar Cipher

The algorithm of Caesar cipher holds the following features −

  • Caesar Cipher Technique is the simple and easy method of encryption technique.

  • It is simple type of substitution cipher.

  • Each letter of plain text is replaced by a letter with some fixed number of positions down with alphabet.

The following diagram depicts the working of Caesar cipher algorithm implementation −

The program implementation of Caesar cipher algorithm is as follows −

Output

You can see the Caesar cipher, that is the output as shown in the following image −

Explanation

The plain text character is traversed one at a time.

  • For each character in the given plain text, transform the given character as per the rule depending on the procedure of encryption and decryption of text.

  • After the steps is followed, a new string is generated which is referred as cipher text.

Hacking of Caesar Cipher Algorithm

The cipher text can be hacked with various possibilities. One of such possibility is Brute Force Technique, which involves trying every possible decryption key. This technique does not demand much effort and is relatively simple for a hacker.

The program implementation for hacking Caesar cipher algorithm is as follows −

Consider the cipher text encrypted in the previous example. Then, the output with possible hacking methods with the key and using brute force attack technique is as follows −

Till now, you have learnt about reverse cipher and Caesar cipher algorithms. Now, let us discuss the ROT13 algorithm and its implementation.

Explanation of ROT13 Algorithm

ROT13 cipher refers to the abbreviated form Rotate by 13 places. It is a special case of Caesar Cipher in which shift is always 13. Every letter is shifted by 13 places to encrypt or decrypt the message.

Example

The following diagram explains the ROT13 algorithm process pictorially −

Program Code

The program implementation of ROT13 algorithm is as follows −

You can see the ROT13 output as shown in the following image −

Drawback

The ROT13 algorithm uses 13 shifts. Therefore, it is very easy to shift the characters in the reverse manner to decrypt the cipher text.

Analysis of ROT13 Algorithm

ROT13 cipher algorithm is considered as special case of Caesar Cipher. It is not a very secure algorithm and can be broken easily with frequency analysis or by just trying possible 25 keys whereas ROT13 can be broken by shifting 13 places. Therefore, it does not include any practical use.

Transposition Cipher is a cryptographic algorithm where the order of alphabets in the plaintext is rearranged to form a cipher text. In this process, the actual plain text alphabets are not included.

Example

A simple example for a transposition cipher is columnar transposition cipher where each character in the plain text is written horizontally with specified alphabet width. The cipher is written vertically, which creates an entirely different cipher text.

Consider the plain text hello world, and let us apply the simple columnar transposition technique as shown below

The plain text characters are placed horizontally and the cipher text is created with vertical format as : holewdlo lr. Now, the receiver has to use the same table to decrypt the cipher text to plain text.

Code

The following program code demonstrates the basic implementation of columnar transposition technique −

Explanation

  • Using the function split_len(), we can split the plain text characters, which can be placed in columnar or row format.

  • encode method helps to create cipher text with key specifying the number of columns and prints the cipher text by reading characters through each column.

Output

The program code for the basic implementation of columnar transposition technique gives the following output −

Note − Cryptanalysts observed a significant improvement in crypto security when transposition technique is performed. They also noted that re-encrypting the cipher text using same transposition cipher creates better security.

In the previous chapter, we have learnt about Transposition Cipher. In this chapter, let us discuss its encryption.

Pyperclip

The main usage of pyperclip plugin in Python programming language is to perform cross platform module for copying and pasting text to the clipboard. You can install python pyperclip module using the command as shown

If the requirement already exists in the system, you can see the following output −

Code

The python code for encrypting transposition cipher in which pyperclip is the main module is as shown below −

Output

The program code for encrypting transposition cipher in which pyperclip is the main module gives the following output −

Explanation

  • The function main() calls the encryptMessage() which includes the procedure for splitting the characters using len function and iterating them in a columnar format.

  • The main function is initialized at the end to get the appropriate output.

In this chapter, you will learn the procedure for decrypting the transposition cipher.

Code

Observe the following code for a better understanding of decrypting a transposition cipher. The cipher text for message Transposition Cipher with key as 6 is fetched as Toners raiCntisippoh.

Explanation

The cipher text and the mentioned key are the two values taken as input parameters for decoding or decrypting the cipher text in reverse technique by placing characters in a column format and reading them in a horizontal manner.

You can place letters in a column format and later combined or concatenate them together using the following piece of code −

Output

The program code for decrypting transposition cipher gives the following output −

In Python, it is possible to encrypt and decrypt files before transmitting to a communication channel. For this, you will have to use the plugin PyCrypto. You can installation this plugin using the command given below.

Code

The program code for encrypting the file with password protector is mentioned below −

You can use the following command to execute the encryption process along with password −

Output

You can observe the following output when you execute the code given above −

Explanation

The passwords are generated using MD5 hash algorithm and the values are stored in simply safe backup files in Windows system, which includes the values as displayed below −

In this chapter, let us discuss decryption of files in cryptography using Python. Note that for decryption process, we will follow the same procedure, but instead of specifying the output path, we will focus on input path or the necessary file which is encrypted.

Code

The following is a sample code for decrypting files in cryptography using Python −

You can use the following command for executing the above code −

Output

You can observe the following code when you execute the command shown above −

Note − The output specifies the hash values before encryption and after decryption, which keeps a note that the same file is encrypted and the process was successful.

Base64 encoding converts the binary data into text format, which is passed through communication channel where a user can handle text safely. Base64 is also called as Privacy enhanced Electronic mail (PEM) and is primarily used in email encryption process.

Python includes a module called BASE64 which includes two primary functions as given below −

  • base64.decode(input, output) − It decodes the input value parameter specified and stores the decoded output as an object.

  • Base64.encode(input, output) − It encodes the input value parameter specified and stores the decoded output as an object.

Program for Encoding

Antivirus for mac downloadbenchtree. You can use the following piece of code to perform base64 encoding −

Output

The code for base64 encoding gives you the following output −

Program for Decoding

You can use the following piece of code to perform base64 decoding −

Output

The code for base64 decoding gives you the following output −

Difference between ASCII and base64

You can observe the following differences when you work on ASCII and base64 for encoding data −

  • When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes.

  • When you encode data in Base64, you start with a sequence of bytes and convert it to a text string.

Drawback

Base64 algorithm is usually used to store passwords in database. The major drawback is that each decoded word can be encoded easily through any online tool and intruders can easily get the information.

In this chapter, let us understand the XOR process along with its coding in Python.

Algorithm

XOR algorithm of encryption and decryption converts the plain text in the format ASCII bytes and uses XOR procedure to convert it to a specified byte. It offers the following advantages to its users −

  • Fast computation
  • No difference marked in left and right side
  • Easy to understand and analyze

Code

You can use the following piece of code to perform XOR process −

Output

The code for XOR process gives you the following output −

Explanation

  • The function xor_crypt_string() includes a parameter to specify mode of encode and decode and also the string value.

  • The basic functions are taken with base64 modules which follows the XOR procedure/ operation to encrypt or decrypt the plain text/ cipher text.

Note − XOR encryption is used to encrypt data and is hard to crack by brute-force method, that is by generating random encrypting keys to match with the correct cipher text.

While using Caesar cipher technique, encrypting and decrypting symbols involves converting the values into numbers with a simple basic procedure of addition or subtraction.

If multiplication is used to convert to cipher text, it is called a wrap-around situation. Consider the letters and the associated numbers to be used as shown below −

The numbers will be used for multiplication procedure and the associated key is 7. The basic formula to be used in such a scenario to generate a multiplicative cipher is as follows −

The number fetched through output is mapped in the table mentioned above and the corresponding letter is taken as the encrypted letter.

The basic modulation function of a multiplicative cipher in Python is as follows −

Note − The advantage with a multiplicative cipher is that it can work with very large keys like 8,953,851. It would take quite a long time for a computer to brute-force through a majority of nine million keys.

Affine Cipher is the combination of Multiplicative Cipher and Caesar Cipher algorithm. The basic implementation of affine cipher is as shown in the image below −

In this chapter, we will implement affine cipher by creating its corresponding class that includes two basic functions for encryption and decryption.

Code

You can use the following code to implement an affine cipher −

Output

You can observe the following output when you implement an affine cipher −

The output displays the encrypted message for the plain text message Affine Cipher and decrypted message for the message sent as input abcdefg.

In this chapter, you will learn about monoalphabetic cipher and its hacking using Python.

Monoalphabetic Cipher

A Monoalphabetic cipher uses a fixed substitution for encrypting the entire message. A monoalphabetic cipher using a Python dictionary with JSON objects is shown here −

With help of this dictionary, we can encrypt the letters with the associated letters as values in JSON object. The following program creates a monoalphabetic program as a class representation which includes all the functions of encryption and decryption.

This file is called later to implement the encryption and decryption process of Monoalphabetic cipher which is mentioned as below −

Output

You can observe the following output when you implement the code given above −

Thus, you can hack a monoalphabetic cipher with specified key value pair which cracks the cipher text to actual plain text.

Simple substitution cipher is the most commonly used cipher and includes an algorithm of substituting every plain text character for every cipher text character. In this process, alphabets are jumbled in comparison with Caesar cipher algorithm.

Example

Keys for a simple substitution cipher usually consists of 26 letters. An example key is −

An example encryption using the above key is−

The following code shows a program to implement simple substitution cipher −

Output

You can observe the following output when you implement the code given above −

In this chapter, we will focus on testing substitution cipher using various methods, which helps to generate random strings as given below −

Output

You can observe the output as randomly generated strings which helps in generating random plain text messages, as shown below −

After the test is successfully completed, we can observe the output message Substitution test passed!.

Thus, you can hack a substitution cipher in the systematic manner.

In this chapter, you can learn about simple implementation of substitution cipher which displays the encrypted and decrypted message as per the logic used in simple substitution cipher technique. This can be considered as an alternative approach of coding.

Code

You can use the following code to perform decryption using simple substitution cipher −

Output

The above code gives you the output as shown here −

In this chapter, you will learn in detail about various modules of cryptography in Python.

Cryptography Module

It includes all the recipes and primitives, and provides a high level interface of coding in Python. You can install cryptography module using the following command −

Code

You can use the following code to implement the cryptography module −

Output

The code given above produces the following output −

The code given here is used to verify the password and creating its hash. It also includes logic for verifying the password for authentication purpose.

Output

Scenario 1 − If you have entered a correct password, you can find the following output −

Scenario 2 − If we enter wrong password, you can find the following output −

Explanation

Hashlib package is used for storing passwords in a database. In this program, salt is used which adds a random sequence to the password string before implementing the hash function.

Vignere Cipher includes a twist with Caesar Cipher algorithm used for encryption and decryption. Vignere Cipher works similar to Caesar Cipher algorithm with only one major distinction: Caesar Cipher includes algorithm for one-character shift, whereas Vignere Cipher includes key with multiple alphabets shift.

Mathematical Equation

For encryption the mathematical equation is as follows −

$$E_{k}left ( M{_{i{}}} right ) = left ( M_{i}+K_{i} right );;; mod ;; 26$$

For decryption the mathematical equation is as follows −

$$D_{k}left ( C{_{i{}}} right ) = left ( C_{i}-K_{i} right );;; mod ;; 26$$

Vignere cipher uses more than one set of substitutions, and hence it is also referred as polyalphabetic cipher. Vignere Cipher will use a letter key instead of a numeric key representation: Letter A will be used for key 0, letter B for key 1 and so on. Numbers of the letters before and after encryption process is shown below −

The possible combination of number of possible keys based on Vignere key length is given as follows, which gives the result of how secure is Vignere Cipher Algorithm −

Vignere Tableau

The tableau used for Vignere cipher is as shown below −

In this chapter, let us understand how to implement Vignere cipher. Consider the text This is basic implementation of Vignere Cipher is to be encoded and the key used is PIZZA.

Code

You can use the following code to implement a Vignere cipher in Python −

Output

You can observe the following output when you implement the code given above −

The possible combinations of hacking the Vignere cipher is next to impossible. Hence, it is considered as a secure encryption mode.

One-time pad cipher is a type of Vignere cipher which includes the following features −

  • It is an unbreakable cipher.

  • The key is exactly same as the length of message which is encrypted.

  • The key is made up of random symbols.

  • As the name suggests, key is used one time only and never used again for any other message to be encrypted.

Due to this, encrypted message will be vulnerable to attack for a cryptanalyst. The key used for a one-time pad cipher is called pad, as it is printed on pads of paper.

Why is it Unbreakable?

The key is unbreakable owing to the following features −

  • The key is as long as the given message.

  • The key is truly random and specially auto-generated.

  • Key and plain text calculated as modulo 10/26/2.

  • Each key should be used once and destroyed by both sender and receiver.

  • There should be two copies of key: one with the sender and other with the receiver.

Encryption

To encrypt a letter, a user needs to write a key underneath the plaintext. The plaintext letter is placed on the top and the key letter on the left. The cross section achieved between two letters is the plain text. It is described in the example below −

Decryption

To decrypt a letter, user takes the key letter on the left and finds cipher text letter in that row. The plain text letter is placed at the top of the column where the user can find the cipher text letter.

Python includes a hacky implementation module for one-time-pad cipher implementation. The package name is called One-Time-Pad which includes a command line encryption tool that uses encryption mechanism similar to the one-time pad cipher algorithm.

Installation

You can use the following command to install this module −

If you wish to use it from the command-line, run the following command −

Code

The following code helps to generate a one-time pad cipher −

Output

You can observe the following output when you run the code given above −

Note − The encrypted message is very easy to crack if the length of the key is less than the length of message (plain text).

In any case, the key is not necessarily random, which makes one-time pad cipher as a worth tool.

In this chapter, let us discuss in detail about symmetric and asymmetric cryptography.

Symmetric Cryptography

In this type, the encryption and decryption process uses the same key. It is also called as secret key cryptography. The main features of symmetric cryptography are as follows −

  • It is simpler and faster.
  • The two parties exchange the key in a secure way.

Drawback

The major drawback of symmetric cryptography is that if the key is leaked to the intruder, the message can be easily changed and this is considered as a risk factor.

Data Encryption Standard (DES)

The most popular symmetric key algorithm is Data Encryption Standard (DES) and Python includes a package which includes the logic behind DES algorithm.

Installation

The command for installation of DES package pyDES in Python is −

Simple program implementation of DES algorithm is as follows −

It calls for the variable padmode which fetches all the packages as per DES algorithm implementation and follows encryption and decryption in a specified manner.

Output

You can see the following output as a result of the code given above −

Asymmetric Cryptography

It is also called as public key cryptography. It works in the reverse way of symmetric cryptography. This implies that it requires two keys: one for encryption and other for decryption. The public key is used for encrypting and the private key is used for decrypting.

Drawback

  • Due to its key length, it contributes lower encryption speed.
  • Key management is crucial.

The following program code in Python illustrates the working of asymmetric cryptography using RSA algorithm and its implementation −

Output

You can find the following output when you execute the code given above −

RSA algorithm is a public key encryption technique and is considered as the most secure way of encryption. It was invented by Rivest, Shamir and Adleman in year 1978 and hence name RSA algorithm.

Algorithm

The RSA algorithm holds the following features −

  • RSA algorithm is a popular exponentiation in a finite field over integers including prime numbers.

  • The integers used by this method are sufficiently large making it difficult to solve.

  • There are two sets of keys in this algorithm: private key and public key.

You will have to go through the following steps to work on RSA algorithm −

Step 1: Generate the RSA modulus

The initial procedure begins with selection of two prime numbers namely p and q, and then calculating their product N, as shown −

Here, let N be the specified large number.

Step 2: Derived Number (e)

Consider number e as a derived number which should be greater than 1 and less than (p-1) and (q-1). The primary condition will be that there should be no common factor of (p-1) and (q-1) except 1

Step 3: Public key

The specified pair of numbers n and e forms the RSA public key and it is made public.

Step 4: Private Key

Private Key d is calculated from the numbers p, q and e. The mathematical relationship between the numbers is as follows −

The above formula is the basic formula for Extended Euclidean Algorithm, which takes p and q as the input parameters.

Encryption Formula

Consider a sender who sends the plain text message to someone whose public key is (n,e). To encrypt the plain text message in the given scenario, use the following syntax −

Decryption Formula

The decryption process is very straightforward and includes analytics for calculation in a systematic approach. Considering receiver C has the private key d, the result modulus will be calculated as −

In this chapter, we will focus on step wise implementation of RSA algorithm using Python.

Generating RSA keys

The following steps are involved in generating RSA keys −

  • Create two large prime numbers namely p and q. The product of these numbers will be called n, where n= p*q

  • Generate a random number which is relatively prime with (p-1) and (q-1). Let the number be called as e.

  • Calculate the modular inverse of e. The calculated inverse will be called as d.

Algorithms for generating RSA keys

We need two primary algorithms for generating RSA keys using Python − Cryptomath module and Rabin Miller module.

Cryptomath Module

The source code of cryptomath module which follows all the basic implementation of RSA algorithm is as follows −

RabinMiller Module

The source code of RabinMiller module which follows all the basic implementation of RSA algorithm is as follows −

The complete code for generating RSA keys is as follows −

Output

The public key and private keys are generated and saved in the respective files as shown in the following output.

In this chapter, we will focus on different implementation of RSA cipher encryption and the functions involved for the same. You can refer or include this python file for implementing RSA cipher algorithm implementation.

The modules included for the encryption algorithm are as follows −

We have initialized the hash value as SHA-256 for better security purpose. We will use a function to generate new keys or a pair of public and private key using the following code.

For encryption, the following function is used which follows the RSA algorithm −

Two parameters are mandatory: message and pub_key which refers to Public key. A public key is used for encryption and private key is used for decryption.

The complete program for encryption procedure is mentioned below −

This chapter is a continuation of the previous chapter where we followed step wise implementation of encryption using RSA algorithm and discusses in detail about it.

The function used to decrypt cipher text is as follows −

For public key cryptography or asymmetric key cryptography, it is important to maintain two important features namely Authentication and Authorization.

Authorization

Authorization is the process to confirm that the sender is the only one who have transmitted the message. The following code explains this −

Authentication

Authentication is possible by verification method which is explained as below −

The digital signature is verified along with the details of sender and recipient. This adds more weight age for security purposes.

RSA Cipher Decryption

You can use the following code for RSA cipher decryption −

Hacking RSA cipher is possible with small prime numbers, but it is considered impossible if it is used with large numbers. The reasons which specify why it is difficult to hack RSA cipher are as follows −

  • Brute force attack would not work as there are too many possible keys to work through. Also, this consumes a lot of time.

  • Dictionary attack will not work in RSA algorithm as the keys are numeric and does not include any characters in it.

  • Frequency analysis of the characters is very difficult to follow as a single encrypted block represents various characters.

  • There are no specific mathematical tricks to hack RSA cipher.

The RSA decryption equation is −

With the help of small prime numbers, we can try hacking RSA cipher and the sample code for the same is mentioned below −

Encrypt Decrypt C++

Output

The above code produces the following output −

Everyone has secrets, Those who don’t still want some things to stay hidden. Most of you would have already used software that are capable to lock your files and after that can only be accessible with a password (like WinRar). We are not discussing here how WinRar does that, but we will be discussing how you can create a simple application in C++ which will allow you to encrypt your text files in a way after which it will just look like a trashed content.

Encryption techniques are not new, they have begun thousands of years ago. It is generally termed as cryptography where we convert our original content to something which cannot be understood. Of course we can convert back the unreadable content to original but this can only be done if we knew how it was encrypted.

To get an idea what it is let’s take a scenario:

I have a message that is highly important to get delivered to my friend. He lives across the street but I cannot go and meet him personally. So only way to communicate is by taking a white board and writing down my message, big enough that it can be seen from at least 50m. Then I will wave it from the terrace so that he can read it. Problem is when I show him the board, everyone else too has access to read the message. But to tackle this situation we have already planned a crypto technique which we can use while sharing secret messages.

Message I want to share: “Dude! I asked her out today.”

Message I am going to write on board: “04210405 09 01191190504 080518 152120 2015040125”

As you can see, this doesn’t make any sense if you don’t know the technique how it was ciphered. In this case, the methodology is extremely easy just to demonstrate. I have replaced each alphabet with its corresponding digit in sequence using two decimal digits (01,02,…,26). To get back the original text, I just need to follow the same process backwards by putting back alphabets in place of its number. Even this simple technique can be upgraded using “salt”. No! I am not talking about the one we eat, salt is a generic term used to add additional attributes in a predefined function. Here our function is defined by converting alphabet to number. On Wikipedia, “In cryptography, a salt is random data that is used as an additional input to a one-way function that hashes a password or passphrase”. Attribute could be anything depending upon the encryption algorithm. Say every time I convert alpha to numeric 50(salt) is added if it’s a vowel and space is replaced by 99.

A little improved message:

“04710455990999511911955049908551899657120992065045125”

While decrypting this, few points need to be kept in mind that is if the message contain any number above 26 then that should be subtracted from 50 because it’s a vowel and that 99 denotes space between words.

Let’s go back to our topic, in our application you need to have at least a basic idea of C++ language and a compiler to create a finished software once we finished coding. I will only be explaining important part briefly. Software requirements for our experiment are:

  • C++ Compiler. I am using Orwell Dev-C++ by Bloodshed Software

Test your working environment by running this peace of code:


#include<iostream>
int main(){
cout<<”Good to go!”;
return 0;
}

Keep in mind C++ is a case-sensitive language (small a and capital A are treated different). Once your program compiled successfully and you see output in console we can move towards our encryption technique.

If you belong to computer science field, the term Bitwise Operations must be familiar to you but if not then please read it before going further. Easiest explanation could be, any operation that is done at individual bit level. Right now, XOR is the point of interest. To understand our algorithm, you are required to know how XOR works. The property that we are going to use of XOR here is:

Say we have a variable X whose value in binary format is “101” and a password key “111”, to cipher the value of X an operation of XOR is needs to be done on both of them. Formula for our algorithm can be described as “X XOR PASS = CIPHERED VALUE”. Here in our example it is

To get back the original value of X, XOR cipher value again with PASS “CIPHERED VALUE XOR PASS = X”. This property of XOR enable us to encrypt any binary data in a simplest way possible. Keep in mind, there are various ways to exploit this technique and any expert in deciphering can break this encryption when enough time is available. But you are not storing any thermal nuclear warhead blueprints or ways how a radioactive spider can make you Spiderman. As long as normal people (not so geeky) are considered, this technique is robust enough.

I am going to cut to the chase and go straight to the coding part. Open your compiler and create a new file. Start adding line of code describe below.


#include <iostream>
#include <fstream>
#include <string>
using namespace std;

These are the library required to successfully compile the program. All symbols in that namespace will become visible without adding the namespace prefix by using last line. Most of you professional coder might be angry for using this but right now, I am more focused on simplicity than flexibility.


void xor_encrypt(char *key, char *string, int n){
int i;int keyLength = strlen(key);

Encrypt C++ Code

for( i = 0 ; i < n ; i++ )

{

string[i]=string[i]^key[i%keyLength];

}

}

xor_encrypt() function is the core part where all the magic happens. This function accepts three parameters:

  1. Password key
  2. String of text required to encrypt
  3. Length of string

Operator for XOR in C is (^) which is used as a unary operator between string and password. First the length of password is calculated to use it along with Remainder Operator for array index. This will keep our password within the limits of its size length. For loop is required to run until string length is exhausted. One thing to notice is we are not returning anything from this function instead pointer is used to update the string by its reference.


int main(void) {
char key[] = 'AllHailTheKingKush1212HAHA1212hehe';
char LOCKEDFILENAME[] = 'locked.txt';
char UNLOCKEDFILENAME[] = “unlocked.txt”;

int choice;

bool lock=false;

streampos size;

union

{

long long int n;

char ch[sizeof(long long int)];

} buffer;

choiceMaker:

cout<<“nWhat would you like to do?:n1)Lockn2)Unlockn”;

cin>>choice;

switch(choice){

case 1:lock=true;break;

case 2:break;

default:cout<<“Invalid choice, input only (1/2).n”;goto choiceMaker;

}

main() function is the nervous system of this program (every C++ program). In the beginning declaration of variables that we are going to use is done.

  • Key variable holds the password that is required to lock and unlock our ciphered text.
  • Lock Boolean variable is used as a switch between encrypting and decrypting.
  • Union buffer will work as a temporary storage to hold data between the processing.
  • Switch statement will enable user to make a choice between lock or unlock a file. Supported inputs are Numeric 1/2, 1 will encrypt a normal file and 2 will decrypt back to original.

if(lock){
ifstream unlocked;ofstream locked;
unlocked.open (UNLOCKEDFILENAME, ios::binary);

locked.open (LOCKEDFILENAME, ios::binary);

if (unlocked.is_open())

{

unlocked.seekg (0, ios::end);

size = unlocked.tellg();

unlocked.seekg (0, ios::beg);

while (unlocked.read(buffer.ch,sizeof(buffer)))

{ cout << buffer.n << ‘n’;

xor_encrypt(key,buffer.ch,sizeof(buffer));

locked.write(buffer.ch,sizeof(buffer));

}

cout<<“nFile size:”<<size<<” Buffer size:”<<sizeof(buffer)<<endl;

cout << “nLocked Successfully.”;

}

unlocked.close();

locked.close();

}

This part of code will read unlocked.txt file, cipher it and write it to locked.txt file.

  • First, the lock condition is evaluated whether it is true or not, if yes then it is good to go.
  • Two file streams are created to read and write file. This functionality is dependent on library we have imported above (fstream). One file will be used as an input and second as output, both of them are opened in binary format to keep the originality intact.
  • Is_open() function will ensure that the file is accessed successfully then seek is used to jump to end to calculate the length of file (this task is not necessary but will provide an insight how big file we are dealing with).
  • While loop perform three operation, firstly it reads the unlocked file step by step(depends on the buffer size) until it reaches to end, then it calls the core function of xor that will encrypt this piece of data and after that it is written back to locked file as ciphered text.
  • In between there is a cout line that enables a visual log of binary data that is going for encryption in this process.

Once this loop ends, some information of file and buffer size is printed on screen and file streams are closed to free up resources.


if(!lock){
ofstream unlocked;ifstream locked;
unlocked.open (UNLOCKEDFILENAME, ios::binary);

locked.open (LOCKEDFILENAME, ios::binary);

if (locked.is_open())

{

locked.seekg (0, ios::end);

size = locked.tellg();

locked.seekg (0, ios::beg);

while (locked.read(buffer.ch,sizeof(buffer)))

{ cout << buffer.n << ‘n’;

xor_encrypt(key,buffer.ch,sizeof(buffer));

unlocked.write(buffer.ch,sizeof(buffer));

C++

}

cout<<“nFile size:”<<size<<” Buffer size:”<<sizeof(buffer)<<endl;

cout << “nUnlocked Successfully.”;

}

unlocked.close();

locked.close();

}

}

These lines are mostly same as above lock code, the difference is we reverse the process and check if lock switch is false. If yes, then locked file will be taken as input and unlocked file will be created with deciphered text. Don’t forget the last “}” bracket, this is continued from the beginning of main function. Every “{” bracket is required to be closed with “}” in the end.

That’s it! Coding stage is completed, compile the program and run it. Before running, go to the directory where you have saved this program and create a dummy text file. File should be named as “unlocked.txt” otherwise our ultimate machine of encryption won’t work. Write some text into this file for testing purpose, save it. Compile & Run the program, Press 1 and hit enter.

If you see some binary numbers floating down the screen and a line stating “Locked Successfully” this means you have created your first very own encryption software in 15-30 minutes. But in case, compilation error or anything not so cool pop up then try to debug the code. Don’t forget even the simple “;” semicolon can stop the whole program from executing, try searching for case-sensitive errors. Don’t worry, I will be adding an attachment of .cpp file created by me. You just have to compile and run. Once it is compiled successfully a new executable (.exe) file will be created if you are using Microsoft Windows. This file enables you to directly run the program without compiling again and again.

Now you can use your own tool for encryption and it’s free! Since you created it! Try decrypting the locked file again, this will give you back the original in unlocked.txt. Keep in mind, the longer your password is, harder it is to crack the encryption (keep it at least more than 20 words).

Here is all the code collectively:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;//encryption function to convert between cipher and original
void xor_encrypt(char *key, char *string, int n)
{
int i;
//length of password
int keyLength = strlen(key);
for( i = 0 ; i < n ; i++ )
{
//XOR Operation
string[i]=string[i]^key[i%keyLength];
}
}

C++ Code To Encrypt And Decrypt A File Dev C++everxx

int main(void) {

char key[] = “AllHailTheKingKush1212HAHA1212hehe”; //password, this can be changed according to your wish but keep it large
int choice; bool lock=false;
char LOCKEDFILENAME[] = “locked.txt”;
char UNLOCKEDFILENAME[] = “unlocked.txt”;

streampos size;
union
{
long long int n;
char ch[sizeof(long long int)];
} buffer; //temporary storage for processing encryption

choiceMaker:
cout<<“nWhat would you like to do?:n1)Lockn2)Unlockn”;
cin>>choice;

//this will create a menu through which user can choose what he wishes to do.
switch(choice){
case 1:lock=true;break;
case 2:break;
default:cout<<“Invalid choice, input only (1/2).n”;goto choiceMaker;
}

//encrypt unlocked.txt file to locked.txt
if(lock)
{
ifstream unlocked;
ofstream locked;
//creating two file streams, one for input and another for output
unlocked.open (UNLOCKEDFILENAME,ios::binary);
locked.open (LOCKEDFILENAME,ios::binary);

if (unlocked.is_open()) //checking if the file has opened successfully
{
unlocked.seekg (0, ios::end); //jumping to end
size = unlocked.tellg(); //checking the file size
unlocked.seekg (0, ios::beg); //coming back to start

while (unlocked.read(buffer.ch,sizeof(buffer))) //reading small bytes at a time
{cout << buffer.n << ‘n’; //visual log

xor_encrypt(key,buffer.ch,sizeof(buffer)); //encrypting

locked.write(buffer.ch,sizeof(buffer)); //writing ciphered text to locked.txt
}

cout<<“nFile size:”<<size<<” Buffer size:”<<sizeof(buffer)<<endl; //buffer size depends on process architecture and compiler. In x64 it was 8bytes
cout << “nLocked Successfully.”;
}

//resources are cleared.
unlocked.close();
locked.close();
}

//decrypt it.
if(!lock)
{ //everything same as above
ofstream unlocked;
ifstream locked;
unlocked.open (UNLOCKEDFILENAME,ios::binary);
locked.open (LOCKEDFILENAME,ios::binary);

if (locked.is_open())
{
locked.seekg (0, ios::end);
size = locked.tellg();
locked.seekg (0, ios::beg);

while (locked.read(buffer.ch,sizeof(buffer)))
{cout << buffer.n << ‘n’;

xor_encrypt(key,buffer.ch,sizeof(buffer));

unlocked.write(buffer.ch,sizeof(buffer));
}

cout<<“nFile size:”<<size<<” Buffer size:”<<sizeof(buffer)<<endl;
cout << “nUnlocked Successfully.”;
}

unlocked.close();
locked.close();

}

}

You can modify this program to accept a password every time it runs and decrypt with it. It will decrypt even with wrong password but your original content cannot be obtained. Even after successful decryption, it will still look like garbage. That’s because the XOR pass we have used can only revert it back to original. Try adding more functionality and let me know in comments!

Attachment: Download Zipped file for this project.