Skip to content

Commit

Permalink
Adding examples
Browse files Browse the repository at this point in the history
  • Loading branch information
Lucas Swartsenburg committed Dec 11, 2023
1 parent c420f70 commit e330cdf
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 98 deletions.
140 changes: 68 additions & 72 deletions src/cipher_algorithms/ciphers/columnar_transposition/algo.py
Original file line number Diff line number Diff line change
@@ -1,106 +1,102 @@
# Columnar Transposition
import math


# encrypt func
def encryptMessage(msg, key):
cipher = ""
cipher = ""

# track key indices
k_indx = 0

msg_len = float(len(msg))
msg_lst = list(msg)
key_lst = sorted(list(key))

# track key indices
k_indx = 0
# calculate column of the matrix
col = len(key)

msg_len = float(len(msg))
msg_lst = list(msg)
key_lst = sorted(list(key))
# calculate maximum row of the matrix
row = int(math.ceil(msg_len / col))

# calculate column of the matrix
col = len(key)

# calculate maximum row of the matrix
row = int(math.ceil(msg_len / col))
# adding padding char
fill_null = int((row * col) - msg_len)
msg_lst.extend("_" * fill_null)

# adding padding char
fill_null = int((row * col) - msg_len)
msg_lst.extend('_' * fill_null)
# create Matrix and insert message and padding characters row-wise
matrix = [msg_lst[i : i + col] for i in range(0, len(msg_lst), col)]

# create Matrix and insert message and padding characters row-wise
matrix = [msg_lst[i: i + col]
for i in range(0, len(msg_lst), col)]
# read matrix column-wise using key
for _ in range(col):
curr_idx = key.index(key_lst[k_indx])
cipher += "".join([row[curr_idx] for row in matrix])
k_indx += 1

# read matrix column-wise using key
for _ in range(col):
curr_idx = key.index(key_lst[k_indx])
cipher += ''.join([row[curr_idx]
for row in matrix])
k_indx += 1
return cipher

return cipher

# decrypt func
def decryptMessage(cipher, key):
msg = ""
msg = ""

# track key indices
k_indx = 0
# track key indices
k_indx = 0

# track msg indices
msg_indx = 0
msg_len = float(len(cipher))
msg_lst = list(cipher)
# track msg indices
msg_indx = 0
msg_len = float(len(cipher))
msg_lst = list(cipher)

# calculate column of the matrix
col = len(key)

# calculate maximum row of the matrix
row = int(math.ceil(msg_len / col))
# calculate column of the matrix
col = len(key)

#converting key into a list so that we can sort alphabetically
key_lst = sorted(list(key))
# calculate maximum row of the matrix
row = int(math.ceil(msg_len / col))

# create an empty matrix to
# store deciphered message
dec_cipher = []
for _ in range(row):
dec_cipher += [[None] * col]
# converting key into a list so that we can sort alphabetically
key_lst = sorted(list(key))

# Arrange the matrix column wise
for _ in range(col):
curr_idx = key.index(key_lst[k_indx])
# create an empty matrix to
# store deciphered message
dec_cipher = []
for _ in range(row):
dec_cipher += [[None] * col]

for j in range(row):
dec_cipher[j][curr_idx] = msg_lst[msg_indx]
msg_indx += 1
k_indx += 1
# Arrange the matrix column wise
for _ in range(col):
curr_idx = key.index(key_lst[k_indx])

# convert decrypted msg matrix into a string
try:
msg = ''.join(sum(dec_cipher, []))
except TypeError:
raise TypeError("This program cannot",
"handle repeating words.")
for j in range(row):
dec_cipher[j][curr_idx] = msg_lst[msg_indx]
msg_indx += 1
k_indx += 1

null_count = msg.count('_')
# convert decrypted msg matrix into a string
try:
msg = "".join(sum(dec_cipher, []))
except TypeError:
raise TypeError("This program cannot", "handle repeating words.")

if null_count > 0:
return msg[: -null_count]
null_count = msg.count("_")

return msg
if null_count > 0:
return msg[:-null_count]

return msg

######Example######
"""
msg = "the quick brown fox jumps over the lazy dog"
print(msg)
cipher = encryptMessage(msg)
print("Encrypted Message: {}".
format(cipher))

print("Decryped Message: {}".
format(decryptMessage(cipher)))
---outputs the following---
"""
---outputs the following---
the quick brown fox jumps over the lazy dog
Encrypted Message: hu wou rezoeibnxmo ygtqkofjsehad cr pvtl _
Decryped Message: the quick brown fox jumps over the lazy dog
"""
if __name__ == "__main__":
msg = "the quick brown fox jumps over the lazy dog"

print(msg)
cipher = encryptMessage(msg)
print("Encrypted Message: {}".format(cipher))

print("Decryped Message: {}".format(decryptMessage(cipher)))
28 changes: 15 additions & 13 deletions src/cipher_algorithms/ciphers/polybius_cipher/algo.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#polybius cipher
# polybius cipher


def generate_polybius_square():
# Generate a Polybius Square mapping letters to coordinates
Expand All @@ -7,7 +8,7 @@ def generate_polybius_square():
count = 1

for char in alphabet:
if char == 'J':
if char == "J":
continue # Skip 'J' in the square
row = (count - 1) // 5 + 1
col = (count - 1) % 5 + 1
Expand All @@ -16,23 +17,25 @@ def generate_polybius_square():

return square


def encrypt_polybius(plain_text):
# Encrypt the plain text using the Polybius Square
plain_text = plain_text.upper()
square = generate_polybius_square()
cipher_text = ""

for char in plain_text:
if char == 'J':
char = 'I' # Replace 'J' with 'I'
if char == "J":
char = "I" # Replace 'J' with 'I'
if char.isalpha():
row, col = square[char]
cipher_text += str(row) + str(col) + ' '
cipher_text += str(row) + str(col) + " "

return cipher_text.strip()


def decrypt_polybius(cipher_text):
cipher_text = cipher_text.replace(' ', '')
cipher_text = cipher_text.replace(" ", "")
square = generate_polybius_square()
plain_text = ""

Expand All @@ -46,17 +49,16 @@ def decrypt_polybius(cipher_text):
return plain_text


###Example###
"""
msg = "the quick brown fox jumps over the lazy dog"
cipher = encrypt_polybius(msg)
print(f'Plaintext: {plaintext}')
print(f'Ciphertext: {cipher}')
print (f'Decrypt: {decrypt_polybius(cipher)}' )
---outputs the following---
Plaintext: the quick brown fox jumps over the lazy dog
Ciphertext: 44 23 15 41 45 24 13 25 12 42 34 52 33 21 34 53 24 45 32 35 43 34 51 15 42 44 23 15 31 11 55 54 14 34 22
Decrypt: thequickbrownfoxiumpsoverthelazydog
"""
if __name__ == "__main__":
msg = "the quick brown fox jumps over the lazy dog"
cipher = encrypt_polybius(msg)
print(f"Plaintext: {msg}")
print(f"Ciphertext: {cipher}")
print(f"Decrypt: {decrypt_polybius(cipher)}")
23 changes: 10 additions & 13 deletions src/cipher_algorithms/ciphers/rail_fence/algo.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,21 +112,18 @@ def decryptRailFence(cipher, key):
return "".join(result)


###Example###
"""
key = 3
msg = "the quick brown fox jumps over the lazy dog"
print(msg)
cipher = encryptRailFence(msg, key)
print("Encrypted Message: {}".
format(cipher))
print("Decryped Message: {}".
format(decryptRailFence(cipher, key)))
---outputs the following---
---outputs the following---
the quick brown fox jumps over the lazy dog
Encrypted Message: tqkofjsehadh uc rw o up vrtelz oeibnxmo yg
Decryped Message: the quick brown fox jumps over the lazy dog
"""
if __name__ == "__main__":
key = 3
msg = "the quick brown fox jumps over the lazy dog"
print(msg)

cipher = encryptRailFence(msg, key)
print("Encrypted Message: {}".format(cipher))

print("Decryped Message: {}".format(decryptRailFence(cipher, key)))

0 comments on commit e330cdf

Please sign in to comment.