How do I use Python to implement ceaser cipher encryption and decryption?

How do I use Python to implement ceaser cipher encryption and decryption?

·

2 min read

We'll learn about the ceaser cipher and how to encrypt and decrypt data with it in Python.

Let's get this learning process started.

What is the Ceaser cipher and when may we apply it?

  • The ceaser cipher was used by Julius Caesar to convey secret communications to his generals in the field. If his messages were intercepted, his opponent would be unable to read any of them.

  • A Caesar cipher is a straightforward way of encoding data. To generate an encoding alphabet, Caesar ciphers employ a substitution process in which letters in the alphabet are displaced by a predetermined number of spaces.

  • for example; With a right shift of 3, A would become D, B would become E, and so on.

images.png

How can I encrypt and decrypt with the ceaser cypher?

Encryption with Ceaser Cipher :

  • The technique of transforming a normal communication (plaintext) into a meaningless message is known as encryption (Ciphertext).

  • In the below example, The parameters of the encryption function are key and message. The value of the shift we apply to the message is the key parameter, and the message parameter is the plain text that we encode with the alphabet using the shift value.

def encrypt(key,message): 
    message = message.upper()
    alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    result = ""
    for letter in message:
        if letter in alpha:
            letter_index = (alpha.find(letter) + key) % len(alpha) 
            result = result +alpha[letter_index]
        else:
            result = result + letter
    return result

Decryption with Ceaser Cipher :

  • The process of transforming a meaningless communication (Ciphertext) back to its original form is known as decryption (Plaintext).

  • This method involves manually decrypting the text or utilizing the same keys that were used to encrypt the original material.

def decrypt(key, message):
    message = message.upper()
    alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    result = ""
    for letter in message:
        if letter in alpha:
            letter_index = (alpha.find(letter) - key) % len(alpha)
            result = result + alpha[letter_index]
        else:
            result = result + letter
    return result

Main function :

  • We use the message Hashnode to convert plain text to cipher text in this case.

  • The encryption function is then called, and it encrypts the message using the shift value of 3. The decrypt function is subsequently called, and it converts the encryption text to plain text (original message).

def main():
    message = "Hashnode"
    encrypted = encrypt(3, message)
    decrypted = decrypt(3, encrypted)

    print('Original message: '+ message)
    print('Encrypted message: '+ encrypted)
    print('Decrypted message: '+ decrypted)

Output :

out.png