Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit e5f35aa

Browse files
committedNov 23, 2024·
cipher: add scytale cipher
1 parent f3f32ae commit e5f35aa

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
 

‎ciphers/scytale_cipher.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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

Comments
 (0)
Please sign in to comment.