Post

Vigenère Cipher

This post features a simple Python script that demonstrates how to encrypt and decrypt messages using the Vigenère cipher, a classic polyalphabetic substitution method used in historical cryptography.

Description

By entering a keyword, users can easily encode or decode text. This project is perfect for anyone looking to learn the basics of encryption and understand how shifting characters based on a repeating key works.

img-description

The full Python code is included below, with examples of both encryption and decryption.

🔐 A fun way to explore foundational cryptography concepts with just a few lines of Python!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#cipher = (key + plain) mod 26
#plain = (cipher - key) mod 26
#BY The "KING" 
print(r"""
     
    
 ██████╗████████╗███████╗    ██████╗ ██╗      █████╗ ██╗   ██╗███████╗██████╗       ██╗██╗  ██╗██╗███╗   ██╗ ██████╗ ██╗  
██╔════╝╚══██╔══╝██╔════╝    ██╔══██╗██║     ██╔══██╗╚██╗ ██╔╝██╔════╝██╔══██╗     ██╔╝██║ ██╔╝██║████╗  ██║██╔════╝ ╚██╗ 
██║        ██║   █████╗      ██████╔╝██║     ███████║ ╚████╔╝ █████╗  ██████╔╝    ██╔╝ █████╔╝ ██║██╔██╗ ██║██║  ███╗ ╚██╗
██║        ██║   ██╔══╝      ██╔═══╝ ██║     ██╔══██║  ╚██╔╝  ██╔══╝  ██╔══██╗    ╚██╗ ██╔═██╗ ██║██║╚██╗██║██║   ██║ ██╔╝
╚██████╗   ██║   ██║         ██║     ███████╗██║  ██║   ██║   ███████╗██║  ██║     ╚██╗██║  ██╗██║██║ ╚████║╚██████╔╝██╔╝ 
 ╚═════╝   ╚═╝   ╚═╝         ╚═╝     ╚══════╝╚═╝  ╚═╝   ╚═╝   ╚══════╝╚═╝  ╚═╝      ╚═╝╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝ ╚═════╝ ╚═╝  
                                                                                                                          

                                     

                               
**********************************************
*       http://nidhal-mabrouk.tech/          *
*       Welcome to My Vigenere Cipher!       *
*       Copyright of King, 2024              *
**********************************************
""")




alp = 'abcdefghijklmnopqrstuvwxyz'

#This loop to create a new key has a same length as the plain text or cipher text
def samelength(c_np,k):
    nk = k

    for j in range(len(c_np)):
        for i in range (len(k)):
            if len(nk) != len(c_np):
                nk += k[i] 
            else:
                break

    return nk

#Encryption Phase:
def encrypt(plain,key):
    np = plain.replace(" ", "") #to remove spaces from the plain text 
    nk = samelength(np, key)

    cipher = ""

    for k in range(len(nk)):
        ck = ((alp.find(nk[k]) + alp.find(np[k])) % 26)
        cipher += alp[ck]

    print("Here is your encrypted text",cipher)



#Decryption Phase: 
def decrypt(cipher,key):
    nk = samelength(cipher,key)

    plain = ""

    for k in range(len(nk)):
            pk = ((alp.find(cipher[k]) - alp.find(nk[k])) % 26)
            plain += alp[pk]

    print("Here is your decrypted text",plain)


def validate_input():    
    var = input("Enter '1' to Encrypt or Enter '2' to Decrypt: ")
    
    while True:
        if var == '1':
            plain = input("Put your plain text: ").lower()  # Convert to lowercase to match the alphabet
            key = input("Put your key to encrypt: ").lower()  # Convert to lowercase to match the alphabet
            
            # Check if all characters in 'plain' and 'key' are in the alphabet
            if all(c in alp + " " for c in plain) and all(c in alp for c in key):
                print("Input is valid.")
                encrypt(plain, key)
                break  # Exit the loop if the condition is met
            else:
                print("Invalid input. Only lowercase alphabetic characters are allowed.")
                continue
        
        elif var == '2':
            cipher = input("Put your cipher text: ").lower()
            key = input("Put your key to decrypt: ").lower()
            
            # Check if all characters in 'cipher' and 'key' are in the alphabet
            if all(c in alp for c in cipher) and all(c in alp for c in key):
                print("Input is valid.")
                decrypt(cipher, key)
                break  # Exit the loop if the condition is met
            else:
                print("Invalid input. Only lowercase alphabetic characters are allowed.")
                continue
        
        else:
            print("Invalid choice. Please enter '1' for encryption or '2' for decryption.")
            var = input("Enter '1' to Encrypt or Enter '2' to Decrypt: ") # Ask again if input is invalid

validate_input()

Encryption

img-description Encryption

Decryption

img-description Decryption

This post is licensed under CC BY 4.0 by the author.