Program to encrypt a string using Vigenere cipher in Python

The Vigenère cipher is a classic encryption technique that shifts each character in a text by a different amount based on a key. Each character in the text is shifted by the corresponding character in the key, where A=0, B=1, C=2, and so on.

For example, if we have text = "code" and key = "team", each letter gets shifted:

  • 'c' + 't'(19) = 'v'
  • 'o' + 'e'(4) = 's'
  • 'd' + 'a'(0) = 'd'
  • 'e' + 'm'(12) = 'q'

Algorithm Steps

To implement the Vigenère cipher, we follow these steps ?

  • Create an empty list to store encrypted characters
  • Get the ASCII value of 'a' as the starting point
  • For each character pair from text and key:
    • Calculate the shift value from the key character
    • Apply the shift with modulo 26 for wraparound
    • Convert back to character and add to result
  • Join all characters and return the encrypted string

Implementation

class Solution:
    def solve(self, text, key):
        cip = []
        start = ord('a')
        for l, k in zip(text, key):
            shift = ord(k) - start
            pos = start + (ord(l) - start + shift) % 26
            cip.append(chr(pos))
        return ''.join(cip)

# Test the implementation
ob = Solution()
text = "code"
key = "team"
result = ob.solve(text, key)
print(f"Text: {text}")
print(f"Key: {key}")
print(f"Encrypted: {result}")
Text: code
Key: team
Encrypted: vsdq

How It Works

The encryption process works by calculating the shift for each character ?

def explain_vigenere(text, key):
    start = ord('a')
    print("Character-by-character encryption:")
    
    for i, (l, k) in enumerate(zip(text, key)):
        shift = ord(k) - start
        original_pos = ord(l) - start
        new_pos = (original_pos + shift) % 26
        encrypted_char = chr(start + new_pos)
        
        print(f"{l} + {k}({shift}) = {encrypted_char} (position {new_pos})")

explain_vigenere("code", "team")
Character-by-character encryption:
c + t(19) = v (position 21)
o + e(4) = s (position 18)
d + a(0) = d (position 3)
e + m(12) = q (position 16)

Alternative Implementation

Here's a more concise version using a direct formula ?

def vigenere_encrypt(text, key):
    return ''.join(
        chr((ord(t) - ord('a') + ord(k) - ord('a')) % 26 + ord('a'))
        for t, k in zip(text, key)
    )

# Test the function
text = "hello"
key = "world"
encrypted = vigenere_encrypt(text, key)
print(f"'{text}' encrypted with key '{key}' = '{encrypted}'")
'hello' encrypted with key 'world' = 'dscwr'

Conclusion

The Vigenère cipher encrypts text by shifting each character based on a corresponding key character. The modulo operation ensures proper wraparound from 'z' back to 'a', making it a simple yet effective classical encryption method.

Updated on: 2026-03-25T10:39:43+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements