|
| 1 | +def encrypt_scytale_cipher(message: str, key: int) -> str: |
| 2 | + """ |
| 3 | + Encrypts a message using the Scytale Cipher. |
| 4 | + |
| 5 | + :param message: Text to encrypt. |
| 6 | + :param key: Number of rows (key). |
| 7 | + :return: Encrypted message. |
| 8 | + """ |
| 9 | + message = message.replace(" ", "") # Optional: remove spaces |
| 10 | + ciphertext = [''] * key |
| 11 | + |
| 12 | + # Distribute characters across rows based on the key |
| 13 | + for i in range(len(message)): |
| 14 | + ciphertext[i % key] += message[i] |
| 15 | + |
| 16 | + return ''.join(ciphertext) |
| 17 | + |
| 18 | + |
| 19 | +def decrypt_scytale_cipher(ciphertext: str, key: int) -> str: |
| 20 | + """ |
| 21 | + Decrypts a message encrypted with the Scytale Cipher. |
| 22 | + |
| 23 | + :param ciphertext: Encrypted text. |
| 24 | + :param key: Number of rows (key). |
| 25 | + :return: Decrypted message. |
| 26 | + """ |
| 27 | + num_cols = -(-len(ciphertext) // key) # Calculate number of columns (round up) |
| 28 | + num_rows = key |
| 29 | + num_shaded_boxes = (num_cols * num_rows) - len(ciphertext) # Extra unused boxes |
| 30 | + |
| 31 | + plaintext = [''] * num_cols |
| 32 | + col = 0 |
| 33 | + row = 0 |
| 34 | + |
| 35 | + # Rebuild the plaintext row by row |
| 36 | + for char in ciphertext: |
| 37 | + plaintext[col] += char |
| 38 | + col += 1 |
| 39 | + # Reset column and move to next row if end of column is reached |
| 40 | + if (col == num_cols) or (col == num_cols - 1 and row >= num_rows - num_shaded_boxes): |
| 41 | + col = 0 |
| 42 | + row += 1 |
| 43 | + |
| 44 | + return ''.join(plaintext) |
| 45 | + |
| 46 | + |
| 47 | +# Example usage |
| 48 | +message = "HELLO WORLD FROM SCYTALE" |
| 49 | +key = 5 |
| 50 | + |
| 51 | +# Encrypt the message |
| 52 | +ciphered = encrypt_scytale_cipher(message, key) |
| 53 | +print("Encrypted:", ciphered) |
| 54 | + |
| 55 | +# Decrypt the message |
| 56 | +deciphered = decrypt_scytale_cipher(ciphered, key) |
| 57 | +print("Decrypted:", deciphered) |
0 commit comments