Caesar cipher python code

Implementation of Caesar Cipher Program in Python

Python Certification Course: Master the essentials

We will cover the Python implementation of the Caesar Cipher, a cryptographic technique used to encrypt and decrypt messages. If you are not familiar with this technique, it involves shifting the letters of a message by a certain number of positions. This technique was used by Julius Caesar to send confidential messages, and it is still relevant in modern cryptography. Through this article, you will learn how to implement the Caesar Cipher in Python and use it to encrypt and decrypt messages.

Introduction to Caesar Cipher in Python

Caesar Cipher is one of the most well-known and straightforward encryption methods in cryptography . The shift Cipher, Caesar’s Cipher, Caesar shift, and Caesar’s code, are some of its alternate names. Plain text is encrypted using this encryption method so that only the intended recipient can decipher it. Julius Caesar, who employed it in his communications, gave the approach its name.

With this encryption method, each letter in the text must be changed for a certain difference to encrypt our data. Let’s imagine there is a letter «B,» which becomes «C» with the left shift of 1, and «A» with the right shift of 1. Therefore, there is a difference of 1 and a text will follow the same path. Left and right shifts cannot be used simultaneously in the same text.

Let’s have an example here, Think about receiving the message «IFMMP FWFSZPOF» . What to interpret that as is crazy. So let’s take the help of this diagram below to understand this text.

Introduction to Caesar Cipher in Python One

Now using this diagram drawn above we can decrypt our message «IFMMP FWFSZPOF» as shown below.

Introduction to Caesar Cipher in Python Two

As you can see, our Cipher message starts with the letter I. (IFMMP FWFSZPOF). After going through the above-shifted alphabets we can encrypt that the letter H is converted to the Cipher character I. So after decrypting our message** «IFMMP FWFSZPOF» ** the output is «HELLO EVERYONE» .

Pre-requisites:

Algorithm of Caesar Cipher in Python

The algorithm of Caesar Cipher holds the following features :

  • Caesar Cipher Technique is a simple and easy method of encryption technique.
  • Every letter in plain text is changed to a letter that appears a certain number of positions farther down the alphabet.

To understand this algorithm in a better way let’s say we want to encrypt the text «HELLO EVERYONE» . Then, what we can do is change every letter in the text with a new letter that has a fixed difference. If we want to left-shift the text by 1, we must replace each letter in the previous sentence with the letter that comes after it.

Читайте также:  Java swing about window

Plain text: HELLO EVERYONE

Cipher text: IFMMP FWFSZPOF

As of right now, the user cannot read this text without the decryption key. The decrypt key is nothing more than the understanding of how the letters were moved during encryption. We must right shift each letter by one to decipher this.

That was Caesar Cipher’s fundamental idea. The algorithm to obtain an encrypted letter will be as follows if we use a mathematical approach:

e = (a + n) mod 26

where e represents the encrypted letter’s place value, a is the actual letter’s position value, and n tells us the number of shifts to be done for each letter.

On the other side, we’ll use the following formula to decrypt each letter:

e = (a – n) mod 26

Implementation of Caesar Cipher in Python

Now after having an understanding of Caesar Cipher through proper examples and diagrams, let’s take a look at the implementation part of this.

Explanation

Each character in plain text «HELLO EVERYONE» is read one at a time. Transform each character in the provided plain text by the given shift pattern and appropriate rule depending on how the text is encrypted and decrypted. Following the procedure results in the creation of a new string known as Cipher text.

Brute Force Approach to Break Caesar Cipher

There are several ways to crack the Cipher text. One such option is brute force, which includes testing every decryption key that might exist. For a hacker, this method requires little work but it is easy.

The following is how the Caesar Cipher algorithm hacking algorithm works:

In the above example, the hacker has used all the possible keys to fetch the relevant message among all of them. So after going through all the possible messages, the hacker found out the message » RAW THIS SIDE » was more relevant in comparison to all others. So we can say that 3 is used as a key to encrypt the message.

How to Decrypt Caesar Cipher in Python?

To decrypt the original text, we can build a function that will shift in the opposite direction. But we can make use of the module’s cyclic cipher’s property.

Cipher(n) = De-cipher(26-n)

Decryption can be performed using the same function. As an alternative, we will change the shift value to shifts = 26 — shift.

Function to decrypt a cipher text is given below:

Output

FAQs

Q1. What is Cipher Text Used For?

Ans.

Cipher texts are frequently used to encrypt communications to safeguard online conversations. Data from the application layer is encrypted using Ciphers which is done by the transport layer.

Q2. What is the Difference Between Cipher Text and Plain Text?

Ans.

Cleartext is another name for plain text. A message or piece of data that is in the plain text has not been secreted. Cipher Text that is also known as Cryptogram is a message that has been altered to make it so that only the intended receivers can read it. To put it another way, it has become a secret.

Читайте также:  Shg ultra php 15

Conclusion

  • Caesar Cipher in Python is an easy method to encrypt your message.
  • Letter in a plain given text is changed to a letter that appears a certain number of positions farther down the alphabet.
  • Decrypt key shows the number that how many times letters were shifted during encryption.
  • Brute force method to decrypt the text requires little work but it is easy.

Источник

Build a Caesar Cipher in Python

The Caesar cipher comes from its namesake: Julius Caesar. It’s an antiquated method of encoding a message simply by shifting the characters of the alphabet. With Python, we can easily create our own program to encode and decode messages using a Caesar Cipher.

Jason Scott

Jason Scott

Jason Scott

Jason Scott

Build a Caesar Cipher in Python

What is a Caesar Cipher?

A Caesar cipher is a method for encoding a message where letters of the alphabet are shifted, thus obfuscating the original message. For example, a Caesar cipher that shifts the alphabet by 13 means that A becomes N, B becomes O, C becomes P, and etc. Shifting the alphabet by 13 using a Caesar shift is also referred to as ROT13. There’s no practical security use for Caesar ciphers; they do not provide confidentiality or integrity of messages.

Start Programming

Now that we have some basic knowledge of Caesar ciphers, let’s get started on creating our encoder and decoder in Python! I’ve opted for Python 3.8 in this tutorial. There are many ways to write a Caesar cipher script in Python; this tutorial goes over a script I wrote that works for me.

I created my script in Python 3.8 using PyCharm 2020.1 (Community Edition). I named my script caesar.py .

Create a characters variable

The first thing I did was create a variable that housed all of the possible alphabetic characters (upper and lower case). I created a list in a variable called chars and added an uppercase alphabet and a lowercase alphabet.

chars = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz']

Create an encoder function

Next, I wanted to create a function that would allow me to encode a message. The first line of code defines the function.

def encode(message, offset=13):

The function requires two variables to work. The first variable is the message . This is the plaintext message that you want to encode. The second variable is the offset . This variable tells the function how many characters the message must be shifted. By default, it will shift by 13 characters. This means we can execute the function without even giving it the offset and it will, by default, use ROT13. I added this in to allow for flexibility if I wanted to shift the message by anything other than 13 characters.

Next, I created a variable to tell Python how to transpose the message. This is where the script might start looking a little more intimidating and complex. To do this, I used the str.maketrans() method. This method takes the first argument as the plain alphabet and the second argument as the cipher.

def encode(message, offset=13): enc_chars = str.maketrans( f'', f'' )

The first argument, f» , concatenates the two items in the chars list variable. The result is ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz’ .

Читайте также:  Css make text transparent

The second argument, f’chars[0][offset:]>chars[0][:offset]>chars[1][offset:]>chars[1][:offset]>‘ , starts the alphabet at the offset position (in this case, the 13th position or N), then concatenates it with the remaining alphabet starting with A and up to the letter before the offset (or, M). The result is ‘NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm’ .

Finally, I had the function return the value of the transposed (encoded) message using the str.translate() method. Here’s what the entire script looks like up to this point:

chars = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'] def encode(message, offset=13): enc_chars = str.maketrans( f'', f'' ) return str.translate(message, enc_chars)

Create a decoder function

After creating the encoder, creating a decoder was easy! It’s just the reverse of the encoder. I copied the exact same function and just flipped the arguments in the str.maketrans() method. After that was done, that finished everything for the script. Here’s what the entire completed script looks like:

chars = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'] def encode(message, offset=13): enc_chars = str.maketrans( f'', f'' ) return str.translate(message, enc_chars) def decode(message, offset=13): dec_chars = str.maketrans( f'', f'' ) return str.translate(message, dec_chars) 

Running the Script

If you’ve followed along with this blog and ran the script, you might realize it doesn’t return anything. I built it specifically to be used with an interactive Python shell. From a command-line terminal, use the -i option with python to enter an interactive shell. From here, you can run the encoder and decoder functions.

>>> encode('Hello') >>> 'Uryyb' >>> >>> encode('Hello', 15) >>> 'Wtaad'

Running the script through the interpreter

If you don’t feel comfortable using command-line to execute Python or you just want to use the script in whatever IDE you’re using, I’ve appended the script with code that will prompt the user to encode and decode messages.

chars = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'] def encode(message, offset=13): enc_chars = str.maketrans( f'', f'' ) return str.translate(message, enc_chars) def decode(message, offset=13): dec_chars = str.maketrans( f'', f'' ) return str.translate(message, dec_chars) get_option = input("Choose [e]ncode or [d]ecode (Default: e): ") if get_option == 'e': message = input('Enter your plaintext message: ') offset = int(input('Choose the shift (1-26): ')) if offset < 1 or offset >26: raise Exception(f'Invalid entry: ') else: print(f'Your encoded message: ') elif get_option == 'd': message = input('Enter your ciphertext message: ') offset = int(input('Choose the shift (1-26): ')) if offset < 1 or offset >26: raise Exception(f'Invalid entry: ') else: print(f'Your decoded message: ') else: raise Exception(f'Invalid option: ') 

Conclusion

This is just one of the many ways you can build a Caesar cipher in Python. Once you learn how to build an encoder and decoder in a cipher as simple as this one, you’ll be able to progress to more difficult ciphers and encryption schemes.

Subscribe to Cyber Hacktics

Get the latest posts delivered right to your inbox

Источник

Оцените статью