transposition_cipher


"/home/yossef/notes/courses/hashing/transposition_cipher.md"

path: courses/hashing/transposition_cipher.md

- **fileName**: transposition_cipher
- **Created on**: 2025-03-07 21:43:57

implementation of transposition cipher


import math

# Encrypts a message using a transposition cipher
def encryptedMessage(key, plain_text) -> str:
    # Create a list with 'key' number of empty strings.
    # Each string represents a column in the cipher grid.
    cipherText = [""] * key

    # Iterate over each column index
    for col in range(key):
        pointer = col
        # Keep adding characters to the column by jumping 'key' steps
        while pointer < len(plain_text):
            cipherText[col] += plain_text[pointer]
            pointer += key
    
    # Join all columns to form the final encrypted text
    return "".join(cipherText)

# Example usage of encryption
encrypted_value = encryptedMessage(3, "yossef sabry")
print("Encrypted value:", encrypted_value)  # Output: "yfsb oeasory"

# Decrypts a message using a transposition cipher
def decryptedMessage(key, message) -> str:
    # Calculate the number of columns needed in the grid
    num_cols = math.ceil(len(message) / key)
    num_rows = key
    
    # Calculate the number of empty spaces at the end of the grid
    num_of_shaded_boxes = (num_cols * num_rows) - len(message)
    
    # Create a list of empty strings, one for each column
    plain_text = [""] * num_cols
    
    col = 0
    row = 0
    
    # Iterate over each character in the encrypted message
    for s in message:
        plain_text[col] += s
        col += 1

        # If we reach the end of a row or encounter shaded boxes, move to the next row
        if ((col == num_cols) or 
            (col == num_cols - 1 and row >= num_rows - num_of_shaded_boxes)):
            col = 0
            row += 1
    
    # Join all columns to form the final decrypted text
    return "".join(plain_text)

# Example usage of decryption
print("Decrypted value:", decryptedMessage(3, encrypted_value))  # Output: "yossef sabry"

continue:./hill_cipher.md
before:./caeser_cipher.md