× {{alert.msg}} Never ask again
Receive New Tutorials
GET IT FREE

Simple Python Encryption: How to Encrypt a Message

– {{showDate(postTime)}}

python encryption

What is Cryptography?

Let’s examine the following examples of Plaintext and Reverse Cipher

  1. Every skill acquired in cyber security is hard won. It includes a wide array of prerequisites (even) to get started.
  2. . edrtarts  teg  ot  setisiuqererp  fo  yarra  a  sedulcni    now drah si ytirucesrebyc  ni deriuqca  lliks yrevE.

With statement (A), anybody can read and understand it clearly. What about statement B—it’s absolute gibberish, or so it seems like it. However, a cryptanalyst may be able to decrypt the concept of statement (B).

In the examples above, statement (A) is plaintext, while statement (B) is a reverse cipher text.  Thus, cryptography is defined as the art of manipulating or scrambling plaintext into ciphertext.

Quick Background

Cryptography originated approximately 4000 years ago in Egypt. The word cryptography comes from the word: KRYPTOS and GRAPHEIN. KRYPTOS means “hidden”, while GRAPHEIN means “writing”.

The Egyptians used to communicate through messages written in hieroglyph.  The code was known only by the scribes (referred to as writers) and recipients.  It is quite similar to modern cryptography where two keys—PUBLIC and PRIVATE—are used to encrypt and decrypt the message.

A cryptanalyst is someone who hacks or breaks or decrypts a ciphered text. In this context, decrypt means to convert a ciphered text into/to a plaintext.

Early types

Caesar-shift cipher

The Caesar shift cipher is one of the earliest methods in cryptography. In this method, the message is hidden from unauthorized readers by shifting the letters of a message by an agreed number. Upon receiving the message, the recipient would then shift the letters back by the same number agreed upon earlier.   A cryptanalyst may be able to decrypt the message by observing the cipher method.

Reverse cipher

In reverse cipher method, letters are not shifted. Rather, the message is encrypted in a reverse order. To decrypt a message in reverse, we just reverse the reversed message to the original form. Julius Caesar invented the reverse cipher circa 2000 years ago.

Apart from the reverse and Caesar shift cipher, others such as substitution shift cipher were also used in the early days of cryptography.  However, most of these methods can be decrypted easily.

Purpose

The primary objective of cryptography is to provide the following basic security concepts in information security.

Integrity:

Although cryptography helps us to detect whether a data has been altered, it cannot prevent data alteration.  For instance, let’s assume sender A drafted and encrypted a message to sender B via the reverse cipher. Remember the reverse cipher is encrypted in a reverse form.  Any addition of a letter in the message may compromise integrity.  Let’s check out the example below:

Message in Plaintext:    Technology is Booming!

Message in Reversed Cipher:  ginmooB  si ygolonhceT!

Now let’s add the letters (i, e, and s) at the beginning of the message in its reversed format.  It looks like this:

Altered Message in Plaintext:  Technologies is booming!

The inclusion of those three letters altered the data and made its syntax quite weird. Integrity simply helps in detecting data alteration.

Authentication:

Authentication helps in identifying the sender of the message or where the message originated. In addition, it also provides assurance about the date and time of transmission of data.

Confidentiality:

Confidentiality is the fundamental security concept provided by cryptography. For instance, in the Caesar shift method, the sender can use an agreed number to keep the meaning of a message from unauthorized users. The recipient can decrypt the message via the agreed number.

Example of a message in Caesar Shift Cipher. Our agreed number is 3:

Original Message:   Python is preferred to Perl.

Message in Shift Cipher:  sbwkrq lv suhihuuhg wruo.

Encrypting a Message in Python

Basics

Now let’s move to the main motive of this tutorial. In this tutorial, we are going encrypt a message in Python via reverse cipher.  We can also encrypt in C++/C programming but Python makes it easier and is mostly preferred.

Apart from reverse cipher, it is quite possible to encrypt a message in Python via substitution and Caesar shift cipher.

Typically, the cryptography library and others such as PyCrypto, M2Crypto, and PyOpenSSL in Python is the main reason why the majority prefers to use Python for encryption and other related cryptographic activities.

However, for this tutorial, we won’t focus on crypto libraries or modules. Importing libraries and modules are not really necessary for us at this moment unless, maybe, we want to encrypt files on our pen drive or hard disk drive.

Before we start our encryption project, let’s refresh our minds with some basic programming concepts in Python such as the len()  function, Data type, Comparison operators, and the interactive shell.

The python interpreter is usually located at /usr/local/bin python on machines where it is available.  We can then invoke the python interpreter at the shell prompt by typing the command:

python

Afterward, Python comes back with the version of the installed Python date and time of installation, respectively.  We can try our hands on the interpreter by writing a small program like the one below:

print  “Hello, World!”

Instead of appending the print() at the beginning of the statement, we can just type at the command prompt for the interpreter to return our code.

“Hello, World!”

Please bear in mind this is possible in Python 2 and not previous versions.

Now let’s fix our attention on basic programming concepts such as the lens() , data type, comparison operators and others which we will need for our encrypting project.

First and foremost, let’s begin with variables. Variables are technically defined as reserve memory location to store values.  Thus, when you create a variable, the space is reserved for the variable in the memory. The operand to the left of the operator is the name of the variable. The operand to the right of the operator is the value stored in the variable. The equal sign (=) is used to assign values to variables.

For example, in our reverse cipher example, we can store the content in the variable named “Message”.

Message = “My other computer is your computer.”     # a string  
Miles  =  1000.0     #a float   
Payroll  =  5000     # an  int

Here, we have assigned three different data types to three different variables. Data types allow the interpreter to allocate memory and decide what can be stored in memory.

List len() Method:

The method len() returns the number of elements in a list or the number of elements in a list. Here is the syntax for the len() method:

len(list)

The list is a parameter for the number of elements to be counted. Here is an example of len() method:

Authors  = [‘John’, ‘Samuel’,’ David’,’ Jonathan’]    
len(Authors)   
4           

Comparison operators:

Comparison operators are used to compare values. It either returns True or False according to the condition. Greater sign ( > ), Less than sign ( < ), Equal to sign ( == ), Not equal to sign ( != ), Greater than sign ( >= ), Less than sign ( <= ) are examples of operators that compare values.

Here is an example of comparison operator:

A = 23  
B = 45      
If (  A == B ) :  
   print  “ A  is  equal to  B”  
else:
    print  “A  is not equal to B”   

Getting started

First and foremost, let’s create a variable named message to store the string to be reversed.

message =  ‘Hello, do you know my other computer is your computer?’

Next, we create another variable named Translated to store our reversed string or message. At the start of the program, the translated variable is just a blank string.

translated =  ‘ ‘

Now, let’s store a value in the variable i. The expression that is evaluated and stored in the variable is len(message) - 1. Remember, the len() method we discussed initially? The len() function accepts a string value arguments and returns an integer value of how many characters are in the string.

The len(message) finds the number of characters in the message and deducts or subtracts one(1) and afterward, stores the result in the variable i.

It looks like this:

i  =  len(message)   -1

Now we will create while statement to tell Python to check what the condition evaluates to. Here is our while statement:

while  i  >=  0 

The i in our while statement is the same as the i variable. Remember the len() function counted the number of characters in the message variable and subtracted 1. The while statements simply mean that so far as the variable I is greater or equal to zero, the code continues to execute in the block.

At the start of the program, we created a variable named translated to store the reversed string. Now we will store a value in our translated variable. The value that is stored is the current value in the translated concatenated with the character at the index I in the message.

translated  =  translated + message[i]

Next, our variable i is assigned the current integer value and one ( 1) is subtracted or deducted from it.

i =  i  -  1    

Finally, the print() function prints out the content of the translated variable. It looks like this:

‘ ?retupmoc  ruoy  si  retupmoc  rehto ym  wonk  uoy  od  olleH’

Here is the code for our program:

#A Reverse Cipher program  
message =  ‘Hello, do you know my other computer is your computer?’ 
translated =  ‘ ‘   
i = len(message)  -  1   
while  i >=  0 :   
         translated = translated + message[i]      
         i  =  i  =  1     
print(translated)

Wrapping up

In this tutorial, we learned how to simply reverse a message or sentence in Python via the reverse cipher. However, it is not a good idea to encrypt sensitive content in reverse cipher. The reverse cipher is said to be the weakest cipher ever in history. However, we can still try our hands on reverse cipher in python for trivial documents.

Other tutorials you might be interested in


Author’s Biopython encryption

Michael is a budding Cybersecurity Engineer and a technical writer based in Ghana, Africa. He works with AmericanEyes Security as a part-time WordPress security consultant. He is interested in Ruby on Rails and PHP security.




Questions about this tutorial?  Get Live 1:1 help from Python experts!
Gbenga Oladipupo
Gbenga Oladipupo
5.0
Senior Mobile Engineer with many years of experience
Senior Mobile Engineer with 7 years+ of active programming experience. I'm proficient in Kotlin, Dart, Java and Python. I have helped many new...
Hire this Expert
Humayun Shabbir
Humayun Shabbir
5.0
Expert Visual Basic, C# and JavaScript Developer | 3500+ sessions
Welcome to my profile on Codementor! I'm a dedicated full-time mentor with a track record of over 3500 sessions since 2015. My journey in...
Hire this Expert
comments powered by Disqus