Python Encyclopedia for Academics
  • Course Outline
  • Artificial Intelligence
    • Data Science Foundation
      • Python Programming
        • Introduction and Basics
          • Variables
          • Print Function
          • Input From User
          • Data Types
          • Type Conversion
        • Operators
          • Arithmetic Operators
          • Relational Operators
          • Bitwise Operators
          • Logical Operators
          • Assignment Operators
          • Compound Operators
          • Membership Operators
          • Identity Operators
      • Numpy
        • Vectors, Matrix
        • Operations on Matrix
        • Mean, Variance, and Standard Deviation
        • Reshaping Arrays
        • Transpose and Determinant of Matrix
      • Pandas
        • Series and DataFrames
        • Slicing, Rows, and Columns
        • Operations on DataFrames
        • Different wayes to creat DataFrame
        • Read, Write Operations with CSV files
      • Matplotlib
        • Graph Basics
        • Format Strings in Plots
        • Label Parameters, Legend
        • Bar Chart, Pie Chart, Histogram, and Scatter Plot
  • Machine Learning Algorithms
    • Regression Analysis In ML
      • Regression Analysis in Machine Learning
      • Proof of Linear Regression Formulas
      • Simple Linear Regression Implementation
      • Multiple Linear Regression
      • Advertising Dataset Example
      • Bike Sharing Dataset
      • Wine Quality Dataset
      • Auto MPG Dataset
    • Classification Algorithms in ML
      • Proof of Logistic Regression
      • Simplified Mathematical Proof of SVM
      • Iris Dataset
  • Machine Learning Laboratory
    • Lab 1: Titanic Dataset
      • Predicting Survival on the Titanic with Machine Learning
    • Lab 2: Dow Jones Index Dataset
      • Dow Jones Index Predictions Using Machine Learning
    • Lab 3: Diabetes Dataset
      • Numpy
      • Pandas
      • Matplotlib
      • Simple Linear Regression
      • Simple Non-linear Regression
      • Performance Matrix
      • Preprocessing
      • Naive Bayes Classification
      • K-Nearest Neighbors (KNN) Classification
      • Decision Tree & Random Forest
      • SVM Classifier
      • Logistic Regression
      • Artificial Neural Network
      • K means Clustering
    • Lab 4: MAGIC Gamma Telescope Dataset
      • Classification in ML-MAGIC Gamma Telescope Dataset
    • Lab 5: Seoul Bike Sharing Demand Dataset
      • Regression in ML-Seoul Bike Sharing Demand Dataset
    • Lab 6: Medical Cost Personal Datasets
      • Predict Insurance Costs with Linear Regression in Python
    • Lab 6: Predict The S&P 500 Index With Machine Learning And Python
      • Predict The S&P 500 Index With Machine Learning And Python
  • Artificial Neural Networks
    • Biological Inspiration vs. Artificial Neurons
    • Review linear algebra and calculus essentials for ANNs
    • Activation Function
  • Mathematics
    • Pre-Calculus
      • Factorials
      • Roots of Polynomials
      • Complex Numbers
      • Polar Coordinates
      • Graph of a Function
    • Calculus 1
      • Limit of a Function
      • Derivative of Function
      • Critical Points
      • Indefinite Integrals
  • Calculus 2
    • 3D Coordinates and Vectors
    • Vectors and Vector Operations
    • Lines and Planes in Space (3D)
    • Partial Derivatives
    • Optimization Problems (Maxima/Minima) in Multivariable Functions
    • Gradient Vectors
  • Engineering Mathematics
    • Laplace Transform
  • Electrical & electronics Eng
    • Resistor
      • Series Resistors
      • Parallel Resistors
    • Nodal Analysis
      • Example 1
      • Example 2
    • Transient State
      • RC Circuit Equations in the s-Domain
      • RL Circuit Equations in the s-Domain
      • LC Circuit Equations in the s-Domain
      • Series RLC Circuit with DC Source
  • Computer Networking
    • Fundamental
      • IPv4 Addressing
      • Network Diagnostics
  • Cybersecurity
    • Classical Ciphers
      • Caesar Cipher
      • Affine Cipher
      • Atbash Cipher
      • Vigenère Cipher
      • Gronsfeld Cipher
      • Alberti Cipher
      • Hill Cipher
Powered by GitBook
On this page
  • Step 1: Understand the Cipher
  • Step 2: Encryption Steps
  • Step 3: Decryption Steps
  • Practical Example
  • Step 4: Python Code
  1. Cybersecurity
  2. Classical Ciphers

Vigenère Cipher

Nerd Cafe

The Vigenère Cipher is a polyalphabetic substitution cipher that uses a keyword to encrypt and decrypt text. It shifts each letter in the plaintext by a number of positions determined by the corresponding letter in the keyword.

Step 1: Understand the Cipher

The alphabet is indexed from 0 to 25:

A = 0, B = 1, C = 2, ..., Z = 25

Each letter in the plaintext is shifted by the numeric value of the corresponding letter in the keyword.

Step 2: Encryption Steps

  • Choose the plaintext: The message to be encrypted.

  • Choose a keyword: A word or phrase that determines the shifts.

  • Repeat the keyword: Extend the keyword to match the length of the plaintext.

  • Shift the letters:

    • For each letter in the plaintext, determine its shift using the corresponding letter in the keyword.

  • The formula for encryption is:

Ci=(Pi+Ki)    mod    26C_{i}=(P_{i}+K_{i})\;\;mod\;\;26Ci​=(Pi​+Ki​)mod26

Where:

  • 𝐶𝑖 is the cipher letter.

  • 𝑃𝑖 is the plaintext letter index.

  • 𝐾𝑖 is the keyword letter index.

Step 3: Decryption Steps

To decrypt, reverse the process:

Pi=(Ci−Ki+26)    mod    26P_{i}=(C_{i}-K_{i}+26)\;\;mod\;\;26Pi​=(Ci​−Ki​+26)mod26

Practical Example

Encryption

  • Plaintext: HELLO

  • Keyword: KEY

Extend the keyword: Repeat KEY to match the plaintext length:

Keyword: K E Y K E

Alphabet indexes:

H = 7, E = 4, L = 11, L = 11, O = 14
K = 10, E = 4, Y = 24, K = 10, E = 4

Apply the formula 𝐶𝑖=(𝑃𝑖+𝐾𝑖) mod 26:

H (7) + K (10) = 17 -> R
E (4) + E (4) = 8  -> I
L (11) + Y (24) = 35 -> 9 (J)
L (11) + K (10) = 21 -> V
O (14) + E (4) = 18 -> S

Ciphertext: RIJVS

Decryption

  • Ciphertext: RIJVS

  • Keyword: KEY

  • Extended keyword: K E Y K E

  • Alphabet indexes:

R = 17, I = 8, J = 9, V = 21, S = 18
K = 10, E = 4, Y = 24, K = 10, E = 4

Apply the formula 𝑃𝑖=(𝐶𝑖−𝐾𝑖+26) mod 26:

R (17) - K (10) = 7  -> H
I (8)  - E (4)  = 4  -> E
J (9) - Y (24) + 26 = 11  -> L
V (21) - K (10) = 11 -> L
S (18) - E (4)  = 14 -> O

Decrypted plaintext: HELLO

Key Points

  • The keyword determines the shifts. Longer and complex keywords make the cipher stronger.

  • The Vigenère cipher is not secure against modern cryptanalysis methods like frequency analysis.

Step 4: Python Code

I've implemented the Vigenère Cipher in Python. The code includes both encryption and decryption functions, along with an example usage section.

def vigenere_encrypt(plaintext, keyword):
    """
    Encrypts the plaintext using the Vigenère Cipher.
    
    Parameters:
    plaintext (str): The message to encrypt.
    keyword (str): The keyword used for encryption.
    
    Returns:
    str: The encrypted message.
    """
    plaintext = plaintext.upper()
    keyword = keyword.upper()
    ciphertext = ""

    keyword_repeated = (keyword * ((len(plaintext) // len(keyword)) + 1))[:len(plaintext)]

    for p, k in zip(plaintext, keyword_repeated):
        if p.isalpha():
            shift = (ord(p) - ord('A') + ord(k) - ord('A')) % 26
            ciphertext += chr(shift + ord('A'))
        else:
            ciphertext += p

    return ciphertext

def vigenere_decrypt(ciphertext, keyword):
    """
    Decrypts the ciphertext using the Vigenère Cipher.
    
    Parameters:
    ciphertext (str): The encrypted message to decrypt.
    keyword (str): The keyword used for decryption.
    
    Returns:
    str: The decrypted message.
    """
    ciphertext = ciphertext.upper()
    keyword = keyword.upper()
    plaintext = ""

    keyword_repeated = (keyword * ((len(ciphertext) // len(keyword)) + 1))[:len(ciphertext)]

    for c, k in zip(ciphertext, keyword_repeated):
        if c.isalpha():
            shift = (ord(c) - ord('A') - (ord(k) - ord('A')) + 26) % 26
            plaintext += chr(shift + ord('A'))
        else:
            plaintext += c

    return plaintext

# Example usage
plaintext = "HELLO"
keyword = "KEY"

print("Plaintext:", plaintext)
print("Keyword:", keyword)

ciphertext = vigenere_encrypt(plaintext, keyword)
print("Ciphertext:", ciphertext)

decrypted_text = vigenere_decrypt(ciphertext, keyword)
print("Decrypted text:", decrypted_text)

Output:

Plaintext: HELLO
Keyword: KEY
Ciphertext: RIJVS
Decrypted text: HELLO
PreviousAtbash CipherNextGronsfeld Cipher

Last updated 1 month ago