Caesar Cipher in Python | Programming Question
Suppose you want to send a message to another person and you want that only that person should be able to read the message and no one else, what would you do? One of the possible solution is to encrypt it using a key and such that only the other person knows what the key is. You would encrypt it using the key and the other person having the same key would be able to decrypt it.
One such famous and simple algorithm was developed by Julius Caesar know as Caesar cipher and in this blog post we will
- Discuss the algorithm used in Caesar cipher
- Write a pseudocode related to the same
- Write a program in python related to the same
Before we begin, this question has been taken from hackerrank and the link is available here
You can learn more about Caesar cipher here
Algorithm used in Caesar cipher
The basic algorithm used in Caesar cipher is you are given a string to encrypt and a key value which is integer. You must shift each value in the given string by the position in alphabetic order according to the key. Suppose you have key as 2 and you have string as ‘abc’, now you must shift every value of the string by that 2 such that a->c, b->d, c->e. Hence, the encrypted string will become ‘cde’
Do remember only alphabets must be shifted and nothing else like special characters, or dashes must not be shifted and hence remains same.
Basic Algorithm Used
We will take a list of character containing only alphabets in lower case. We will
Initially take an array containing only alphabets in lower case, we would use the position of the array to calculate the final string further.
Parse the given string in the list. Initially check if the value is lower case, upper case or not a character. If it’s in upper case we would change it to lower case and put a flag as true that its upper case. Once we increment the position by key passed we would change the case back to upper case and add it to the new string.
If the value of the string is lower case and is in the array of alphabets, we would take the index of the alphabet. Next, we would add the key to the string and take remainder after dividing it with 26. We do this because to take care of the upper count. Suppose we have ‘z’ in the string and we need to increment it by 2, it shouldn’t give an error but rather it should give ‘b’, in that case we need to take remainder when divide by 26 (26 because there are 26 alphabets).
Finally, we return the string and pseudocode is provided as below
Pseudocode for Caesar cipher
We wrote our pseudocode above and explained it above. Now we write a program in python related to the same which can be found here That's all for now! There are many other ways of implementing the Caesar cipher, so make sure to explore other ways as well.