Lab 1 Crypto
Lab 1 Crypto
import socket
def handle_client(client_socket):
try:
while True:
data = client_socket.recv(1024).decode()
if not data:
break
command, text, key = [Link]('|')
key = int(key)
if command == "encrypt":
response = caeser(text, key, "encrypt")
elif command == "decrypt":
response = caeser(text, key, "decrypt")
else:
response = "Invalid command"
client_socket.send([Link]())
except Excep on as e:
print(f"Error: {e}")
nally:
client_socket.close()
def main():
server = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](('localhost', 9999))
[Link](5)
print("Server is listening on port 9999...")
while True:
client_socket, addr = [Link]()
print(f"Connected to {addr}")
handle_client(client_socket)
if __name__ == "__main__":
main()
fi
ti
Client Code-
import socket
def main():
client = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](('localhost', 9999))
print("Connected to Caesar Cipher Server")
try:
while True:
command = input("Enter command (encrypt/decrypt/quit): ").strip().lower()
if command == "quit":
break
text = input("Enter text: ").strip()
key = input("Enter key (integer): ").strip()
[Link](f"{command}|{text}|{key}".encode())
response = [Link](1024).decode()
print(f"Response: {response}")
except Excep on as e:
print(f"Error: {e}")
nally:
[Link]()
if __name__ == "__main__":
main()
fi
ti
Encryp on Technique Report :
Caesar Cipher Encryp on Technique : The Caesar Cipher is a simple encryp on technique where
each le er in the plaintext is shi ed by a speci ed number of places (key) in the alphabet. For
example, with a key of 3, ‘A’ becomes ‘D’, ‘B’ becomes ‘E’, and so on. Decryp on reverses the process
by shi ing the le ers back by the same key. Non-alphabe c characters (e.g., numbers, punctua on)
remain unchanged.
Server Code :
1. caeser Func on: Implements the Caesar Cipher logic. It takes the input text, a key, and a mode
(either “encrypt” or “decrypt”). Alphabe c characters are shi ed based on the key, while non-
alphabe c characters remain unchanged.
2. handle_client Func on: Handles communica on with a connected client. It receives requests in
the format command|text|key, processes the request using the caeser func on, and sends the
result back.
3. Main Func on: Sets up a server to listen on port 9999 for incoming client connec ons. For each
connec on, it invokes handle_client.
Client Code:
1. The client connects to the server at localhost:9999.
2. It prompts the user for a command (“encrypt,” “decrypt,” or “quit”), the text to process, and the
key.
3. It sends the input to the server, receives the response, and displays it to the user.
Summary :
The code uses socket programming for communica on, with the server con nuously running to
handle mul ple client requests. The modular structure ensures separa on of encryp on logic and
networking func onality.
ft
tt
ti
ti
ti
ti
ti
ti
ti
tt
ti
ti
ft
ti
ti
fi
ti
ti
ft
ti
ti
ti
ti
ti
ti
ti
ti
Output-
Monoalphabe c Cipher
Server Code –
import socket
import string
def key():
x = list(string.ascii_lowercase)
ss = []
while x:
le er = [Link]((len(x) - 1) % len(x))
[Link](le er)
return dict(zip(string.ascii_lowercase, ss)), dict(zip(ss, string.ascii_lowercase))
def mono_cipher(text, key, mode):
result = ""
mapping = key if mode == "encrypt" else {v: k for k, v in [Link]()}
for char in text:
if [Link]():
lo = [Link]()
x2 = [Link](lo, char)
result += [Link]() if [Link]() else x2
else:
result += char
return result
def handle_client(client_socket, encrypt_key, decrypt_key):
try:
while True:
data = client_socket.recv(1024).decode()
if not data:
break
inp, text = [Link]('|')
if inp == "encrypt":
run = mono_cipher(text, encrypt_key, "encrypt")
elif inp == "decrypt":
run = mono_cipher(text, decrypt_key, "decrypt")
else:
run = "Invalid inp"
client_socket.send([Link]())
except Excep on as e:
print(f"Error: {e}")
nally:
client_socket.close()
def main():
server = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](('localhost', 9998))
[Link](5)
print("Server is listening on port 9998...")
encrypt_key, decrypt_key = key()
print(f"Encryp on Key: {encrypt_key}")
while True:
client_socket, addr = [Link]()
print(f"Connected to {addr}")
handle_client(client_socket, encrypt_key, decrypt_key)
fi
tt
ti
ti
tt
ti
Client Code –
import socket
def main():
client = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](('localhost', 9998))
print("Connected to Monoalphabe c Cipher Server")
try:
while True:
command = input("Enter command (encrypt/decrypt/quit): ").strip().lower()
if command == "quit":
break
text = input("Enter text: ").strip()
[Link](f"{command}|{text}".encode())
response = [Link](1024).decode()
print(f"Response: {response}")
except Excep on as e:
print(f"Error: {e}")
nally:
[Link]()
if __name__ == "__main__":
main()
fi
ti
ti
Encryp on Technique Report :
Monoalphabe c Cipher Encryp on Technique : The Monoalphabe c Cipher is a subs tu on cipher
where each le er in the plaintext is replaced by another le er, based on a xed subs tu on mapping
(key). Unlike the Caesar Cipher, where the subs tu on is based on shi ing the alphabet by a xed
number, the Monoalphabe c Cipher allows arbitrary mappings of one le er to another. This makes it
more secure than the Caesar Cipher but s ll vulnerable to frequency analysis a acks.
Encryp on Process:
• A key is generated as a mapping of le ers from the standard alphabet to a shu ed or
prede ned arrangement of le ers.
• Each le er in the plaintext is subs tuted with its corresponding le er from the key.
• Non-alphabe c characters remain unchanged.
Decryp on Process:
• The reverse mapping of the key is used to subs tute le ers back to their original values.
• Non-alphabe c characters are directly copied to the output.
Server Code:
1. key Func on:
•Generates a subs tu on key for encryp on and its reverse for decryp on.
•The key maps each le er in the alphabet to another le er, ensuring a one-to-one mapping.
2. mono_cipher Func on:
•Implements the Monoalphabe c Cipher logic for both encryp on and decryp on.
•Accepts the input text, the key, and the mode (“encrypt” or “decrypt”).
•Subs tutes le ers based on the mapping. Uppercase le ers are preserved as uppercase,
and non-alphabe c characters are unchanged.
3. handle_client Func on:
•Processes client requests to encrypt or decrypt text.
•Receives input in the format command|text, applies the appropriate opera on using the
cipher func on, and sends the result back to the client.
4. Main Func on:
•Sets up the server to listen on port 9998.
•Generates the encryp on and decryp on keys using the key func on.
•Handles incoming client connec ons by delega ng processing to handle_client.
Client Code :
1. The client connects to the server at localhost:9998 and allows the user to:
•Encrypt text.
•Decrypt text.
•Exit the program.
2. User input is sent to the server in the format command|text.
3. The server processes the request and sends the response back, which is displayed to
the user.
Summary :
The Monoalphabe c Cipher implementa on combines encryp on logic with a networked client-
server model. The server handles requests to encrypt or decrypt messages based on a pre-generated
subs tu on key. The client provides a simple interface for users to interact with the server. The
system demonstrates secure message encoding using a xed subs tu on mapping and highlights the
use of socket programming for remote access.
ti
fi
ti
tt
ti
ti
ti
ti
ti
ti
tt
ti
ti
ti
tt
ti
ti
ti
ti
ti
tt
ti
tt
ti
ti
ti
ti
ti
tt
ti
ti
ti
ti
ti
ti
ti
ti
ti
tt
fi
ti
tt
ti
tt
tt
ti
tt
ti
ti
ft
ti
tt
ti
fi
ffl
tt
ti
ti
ti
ti
ti
ti
ti
fi
Output –
Playfair Cipher
Server Code –
import socket
def pmatrix(key):
key = [Link]().replace("j", "i")
x = set()
matrix = []
for char in key + "abcdefghiklmnopqrstuvwxyz":
if char not in x and [Link]():
[Link](char)
[Link](char)
return [matrix[i:i+5] for i in range(0, 25, 5)]
if r1 == r2:
c1 = (c1 + (1 if mode == "encrypt" else -1)) % 5
c2 = (c2 + (1 if mode == "encrypt" else -1)) % 5
elif c1 == c2:
r1 = (r1 + (1 if mode == "encrypt" else -1)) % 5
r2 = (r2 + (1 if mode == "encrypt" else -1)) % 5
else:
c1, c2 = c2, c1
return matrix[r1][c1] + matrix[r2][c2]
def playfair_cipher(text, matrix, mode):
text = [Link]().replace("j", "i").replace(" ", "")
if len(text) % 2 != 0:
text += "x"
result = ""
for i in range(0, len(text), 2):
pair = text[i:i+2]
if pair[0] == pair[1]:
pair = pair[0] + "x"
result += p_pair(pair, matrix, mode)
return result
def main():
server = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](('localhost', 9997))
[Link](5)
print("Server is listening on port 9997...")
key = "playfair example"
matrix = pmatrix(key)
print(f"Playfair Matrix: {matrix}")
while True:
client_socket, addr = [Link]()
print(f"Connected to {addr}")
handle_client(client_socket, matrix)
if __name__ == "__main__":
main()
Client Code –
import socket
def main():
client = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](('localhost', 9997))
print("Connected to Playfair Cipher Server")
try:
while True:
inp = input("Enter inp (encrypt/decrypt/quit): ").strip().lower()
if inp == "quit":
break
text = input("Enter text: ").strip()
[Link](f"{inp}|{text}".encode())
x2 = [Link](1024).decode()
print(f"Response: {x2}")
except Excep on as e:
print(f"Error: {e}")
nally:
[Link]()
if __name__ == "__main__":
main()
fi
fi
ti
ti
Encryp on Technique Report :
Playfair Cipher Encryp on Technique : The Playfair Cipher is a digraph subs tu on cipher that
encrypts pairs of le ers (bigrams) rather than single le ers. It uses a 5x5 matrix of le ers constructed
from a keyword, where the le er ‘J’ is typically omi ed or merged with ‘I’ to t the 25-le er
alphabet.
Encryp on Rules:
[Link] Crea on: A key is used to create a 5x5 matrix. The keyword’s le ers are
added rst (ignoring duplicates and trea ng ‘J’ as ‘I’), followed by the remaining le ers of the
alphabet in order.
[Link] Forma on:The plaintext is divided into pairs of two le ers. If a pair has duplicate
le ers (e.g., “LL”), a ller le er like ‘X’ is inserted between them. If the plaintext length is
odd, ‘X’ is appended at the end.
[Link] on Logic:
•If both le ers are in the same row, each is replaced with the le er to its immediate
right (wrapping around to the start of the row if necessary).
•If both le ers are in the same column, each is replaced with the le er immediately
below it (wrapping around to the top of the column if necessary).
•If neither condi on applies, the le ers form a rectangle in the matrix. Each le er is
replaced with the le er in the same row but in the other le er’s column.
Decryp on:
•The decryp on process reverses the encryp on rules, replacing the right or below
shi s with le or above shi s.
Server Code :
[Link] Func on:Creates the 5x5 Playfair matrix from the provided key. Duplicate le ers
are removed, and ‘J’ is replaced with ‘I’. The remaining alphabet lls the matrix.
2.p_pair Func on: Encrypts or decrypts a pair of le ers based on their posi ons in the matrix
using the Playfair Cipher rules.
3.playfair_cipher Func on: Processes the plaintext or ciphertext using the p_pair func on for
each bigram. It ensures that text is lowercase, removes spaces, replaces ‘J’ with ‘I’, and
handles odd-length inputs or repeated le ers.
4.handle_client Func on: Handles communica on with the client. It receives the opera on
type (encrypt or decrypt) and the text, processes it using the cipher, and sends the result
back.
[Link] Func on: Sets up a server on port 9997 and ini alizes the Playfair matrix with the key
“playfair example.” It listens for client connec ons and processes them using handle_client.
Client Code :
1. The client connects to the server on localhost:9997.
2. The user provides input for:
• The opera on: “encrypt,” “decrypt,” or “quit.”
• The text to process.
3. The client sends the input to the server, receives the processed response, and
displays it to the user.
Summary :
The Playfair Cipher implementa on in this server-client model allows encryp on and decryp on of
text based on a shared Playfair key. The server creates and manages the cipher matrix and performs
all encryp on and decryp on opera ons. The client provides a simple user interface for interac ng
with the server, making it suitable for securely encoding and decoding messages.
ti
ti
ti
tt
ti
ft
ti
fi
ti
tt
tt
tt
ti
ti
ti
ft
ti
ti
ti
ti
ti
ti
tt
fi
ti
tt
ti
ti
ft
tt
ti
tt
ti
tt
tt
ti
ti
tt
ti
tt
ti
tt
tt
tt
fi
ti
tt
ti
fi
ti
tt
ti
tt
tt
tt
tt
ti
ti
tt
ti
ti
Output –
Hill Cipher
Server Code –
import socket
def server_process():
srv_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)
srv_socket.bind(("localhost", 65432))
srv_socket.listen(1)
connec on, address = srv_socket.accept()
received_data = connec [Link](1024).decode()
received_text, received_key, opera on = received_data.split("|")
received_key = int(received_key)
if opera on == "encrypt":
processed_text = encode_message(received_text, received_key)
elif opera on == "decrypt":
processed_text = decode_message(received_text, received_key)
else:
processed_text = "Invalid opera on."
connec [Link](processed_text.encode())
connec [Link]()
srv_socket.close()
server_process()
ti
ti
ti
ft
ft
ti
ti
ft
ft
ti
ft
ti
ti
ft
ft
ft
ft
ft
Client Code –
import socket
def client_process():
cl_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)
cl_socket.connect(("localhost", 65432))
while True:
opera on = input("Enter opera on (encrypt/decrypt/quit): ").strip().lower()
if opera on == "quit":
print("Exi ng...")
break
server_reply = cl_socket.recv(1024).decode()
print("Server Response:", server_reply)
cl_socket.close()
client_process()
ti
ti
ti
ti
ti
Encryp on Technique Report :
Encryp on Technique Hill Cipher : The Hill Cipher is a polygraphic subs tu on cipher that encrypts
text using linear algebra. It operates on blocks of le ers (e.g., 2 or 3 le ers at a me) and uses matrix
mul plica on with a key matrix to transform plaintext into ciphertext. However, the provided code
implements a Caesar Cipher-style encryp on with some Hill Cipher terminology.
1. Encryp on:Each le er in the plaintext is shi ed by the key (shi _key) within the
bounds of the alphabet. For example, with a key of 3 and plaintext “abc”, the result
would be “def”.
2. Decryp on: Each le er in the ciphertext is shi ed in the reverse direc on by the key
to recover the plaintext.
3. Mod 26 Arithme c: The shi ing is performed modulo 26 to wrap around the
alphabet if the shi goes past ‘z’ or before ‘a’.
Server Code:
1. Func ons:
•encode_message: Shi s each character of the plaintext by a speci ed key. The shi
wraps around the alphabet (mod 26).
•If the character is lowercase, it shi s forward by shi _key.
•If the character is uppercase, it shi s backward by shi _key.
•Non-alphabe c characters remain unchanged.
•decode_message: Reverses the shi applied by encode_message to recover the original
message.
2. Server Process:
•Sets up a socket server on port 65432.
•Listens for a single client connec on.
•Receives data in the format message|key|opera on.
•Depending on the opera on (encrypt or decrypt), calls the respec ve func on and
processes the input.
•Sends the result back to the client.
•Closes the connec on a er processing.
Client Code:
1. Client Process:
•Connects to the server at localhost:65432.
•Accepts user input:
•Opera on: Either encrypt, decrypt, or quit.
•Message: The text to be processed.
•Key: An integer key (1–25) for shi ing the le ers.
•Sends the input to the server in the format message|key|opera on.
•Receives the processed text from the server and displays it.
•Loops un l the user chooses to quit.
•Closes the connec on a er exi ng.
Summary :
This implementa on, although referred to as a Hill Cipher, is actually a Caesar Cipher-style single-
character subs tu on cipher using a key-based shi . It employs socket programming to create a
client-server architecture, where the server performs encryp on or decryp on and the client
provides inputs. This design demonstrates basic cryptographic opera ons and how they can be
applied over a network for secure communica on.
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ft
ti
ft
ft
ti
ft
tt
tt
ti
ti
ti
ft
ft
ft
ft
ft
ti
ft
tt
tt
ti
ft
ti
ft
ft
ft
ti
tt
ti
ti
ti
ti
ti
fi
ft
ti
ti
ti
ft
Output –
Vigenère Cipher
Server Code –
import socket
def vigenere_encrypt(plain_text, cipher_key):
encrypted_text = ""
cipher_key = cipher_key.lower()
plain_text = plain_text.lower()
key_index = 0
for char in plain_text:
if [Link]():
shi = ord(cipher_key[key_index % len(cipher_key)]) - ord('a')
encrypted_text += chr(((ord(char) - ord('a') + shi ) % 26) + ord('a'))
key_index += 1
else:
encrypted_text += char
return encrypted_text
def run_server():
server_host = 'localhost'
server_port = 65432
if __name__ == "__main__":
run_server()
Client Code –
import socket
def run_client():
server_host = 'localhost'
server_port = 65432
while True:
print("\nVigenère Cipher Client")
print("1. Encrypt message")
print("2. Decrypt message")
print("3. Quit")
ac on = input("Enter your choice (encrypt/decrypt/quit): ")
client_sock.send(ac [Link]())
if ac on == 'quit':
print("Exi ng client...")
break
client_sock.send(cipher_key.encode())
client_sock.send(message_text.encode())
result = client_sock.recv(1024).decode()
print(f"Result: {result}")
if __name__ == "__main__":
run_client()
ti
ti
ti
ti
ti
ti
Encryp on Technique Report :
Server Code :
1. Func ons:
•vigenere_encrypt: Encrypts the plaintext using the Vigenère Cipher.
•Converts the key and plaintext to lowercase for uniform processing.
•Calculates the shi for each character based on the key.
•Appends the encrypted character to the result string, ignoring non-alphabe c characters.
•vigenere_decrypt: Decrypts the ciphertext using the reverse process of encryp on.
2. run_server:
•Listens for client connec ons on port 65432.
•Accepts opera ons (encrypt or decrypt), a key, and a message from the client.
•Processes the input based on the chosen opera on using the respec ve func on.
•Sends the result back to the client.
Client Code :
1. Func onality:
•Connects to the server and provides a user interface to choose between encryp on,
decryp on, or qui ng.
•Sends the chosen opera on, the key, and the message to the server.
•Receives and displays the result from the server.
2. User Interac on:
•Prompts the user for the opera on (encrypt, decrypt, or quit).
•Accepts the key and message, then transmits them to the server.
•Displays the server’s response.
Summary :
•The Vigenère Cipher provides be er security than the Caesar Cipher by varying the shi for
each le er based on a key.
•This implementa on uses socket programming to set up a client-server architecture:
•The server handles encryp on and decryp on opera ons.
•The client sends requests to the server and receives processed results.
•The architecture demonstrates secure communica on using a classic encryp on method.
ti
ti
tt
ti
ti
ti
ti
ti
ti
ti
ti
tti
ti
ft
ti
ti
ti
ti
ti
ti
tt
ft
ft
ti
ft
ti
ti
ti
ti
ti
ft
ti
ti
ti
ti
ti
ti
ti
ti
ft
Output-
One-Time Pad Cipher
Server Code –
import socket
def run_server():
host = 'localhost'
port = 65432
if ac on == 'encrypt':
result = otp_encrypt(message, key)
client_conn.send([Link]())
elif ac on == 'decrypt':
result = otp_decrypt(message, key)
client_conn.send([Link]())
else:
print("Invalid choice received.")
client_conn.send("Invalid choice! Choose 'encrypt', 'decrypt', or 'quit'.".encode())
if __name__ == "__main__":
run_server()
ti
ti
ti
ti
ti
tti
Client Code –
import socket
def run_client():
host = 'localhost'
port = 65432
while True:
print("\nOne-Time Pad Cipher Client")
print("1. Encrypt message")
print("2. Decrypt message")
print("3. Quit")
ac on = input("Enter your choice (encrypt/decrypt/quit): ")
client_sock.send(ac [Link]())
if ac on == 'quit':
print("Exi ng client...")
break
client_sock.send([Link]())
client_sock.send([Link]())
result = client_sock.recv(1024).decode()
print(f"Result: {result}")
if __name__ == "__main__":
run_client()
ti
ti
ti
ti
Encryp on Technique Report :
One-Time Pad Cipher Encryp on Technique : The One-Time Pad (OTP) is an encryp on algorithm
that is theore cally unbreakable when used correctly. It operates using the XOR opera on between
each character of the plaintext and a key of the same length.
1. Principles of OTP:
• The key must be as long as the message.
• Each key is used only once and then discarded (hence the name).
• XOR opera on ensures that encryp on and decryp on are symmetric:
2. Security: OTP is secure if the key is random, at least as long as the plaintext, used
only once, and kept completely secret.
Server Code :
1. Encryp on Func on (otp_encrypt):
•Uses the XOR opera on between each character of the plaintext (message) and the
corresponding character in the key.
•Returns the encrypted text.
2. Decryp on Func on (otp_decrypt):
•Reapplies the XOR opera on between the encrypted message and the key to retrieve the
original plaintext.
3. Server Work ow:
•Listens on a speci ed host and port.
•Accepts a client connec on and con nuously listens for requests.
•Depending on the client request:
•Encrypt: Calls otp_encrypt and sends the result to the client.
•Decrypt: Calls otp_decrypt and sends the plaintext to the client.
•Stops processing if the client sends a “quit” ac on.
Client Code :
1. Work ow:
•Connects to the server.
•Provides a menu for the user to select an ac on: encrypt, decrypt, or quit.
•For encryp on or decryp on:
•Prompts the user for the key and the message.
•Sends the ac on, key, and message to the server.
•Receives and displays the result from the server.
2. Key and Message:
•The user provides the key and plaintext (or ciphertext) for processing.
•The key must match the length of the message for proper encryp on/decryp on.
Summary :
•The One-Time Pad provides unmatched security when its principles are followed.
•This implementa on demonstrates a client-server architecture for processing.
•The server performs the XOR-based OTP encryp on and decryp on.
•The client interacts with the user and transmits the necessary data to the server.
•The approach highlights the prac cal use of the OTP algorithm in a networked applica on.
ti
ti
ti
fl
ti
ti
ti
ti
fi
ti
fl
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
Output-
Rail Fence Cipher
Server Code –
import socket
def rail_fence_encrypt(message, rails):
fence = ['' for _ in range(rails)]
rail = 0
direc on = 1
for char in message:
fence[rail] += char
rail += direc on
if rail == rails or rail == -1:
direc on *= -1
rail += direc on
return ''.join(fence)
message = ''
return message
def run_server():
host = 'localhost'
port = 65432
if ac on == 'encrypt':
result = rail_fence_encrypt(message, key)
client_conn.send([Link]())
elif ac on == 'decrypt':
result = rail_fence_decrypt(message, key)
client_conn.send([Link]())
else:
print("Invalid choice received.")
client_conn.send("Invalid choice! Choose 'encrypt', 'decrypt', or 'quit'.".encode())
if __name__ == "__main__":
run_server()
Client Code –
import socket
def run_client():
host = 'localhost'
port = 65432
while True:
print("\nRail Fence Cipher Client")
print("1. Encrypt message")
print("2. Decrypt message")
print("3. Quit")
ac on = input("Enter your choice (encrypt/decrypt/quit): ")
client_sock.send(ac [Link]())
if ac on == 'quit':
print("Exi ng client...")
break
client_sock.send([Link]())
client_sock.send([Link]())
result = client_sock.recv(1024).decode()
print(f"Result: {result}")
if __name__ == "__main__":
run_client()
ti
ti
ti
ti
ti
ti
Encryp on Technique Report :
The Rail Fence Cipher Encryp on Technique : It is a classical transposi on cipher that encrypts a
message by wri ng it in a zigzag pa ern across a number of “rails” (rows) and then reading the
message o row by row. The process of encryp on and decryp on depends on the number of rails
(or rows) speci ed. It is considered a simple but insecure cipher, primarily used for educa onal
purposes.
Encryp on Process:
[Link] Arrangement: The message is wri en in a zigzag pa ern across a set number of
rails (rows). The text is placed diagonally from the top rail to the bo om, then reversed
direc on to ll the rails again.
[Link] O Rails: A er arranging the message, the ciphertext is generated by reading o
each rail row by row.
Decryp on Process:
[Link] ng the Rail Pa ern: During decryp on, the number of rails is used to
reconstruct the zigzag pa ern of the original message. The encrypted message is placed into
a grid of rails, and the le ers are assigned to their correct posi ons in the zigzag pa ern.
[Link] ng the Message: Once the grid is correctly populated, the message is
reconstructed by reading o the zigzag pa ern, returning the original plaintext.
Server Code:
•The server listens for client connec ons, handles encryp on and decryp on requests, and
sends back the results.
•When the server receives a request, it determines whether the opera on is “encrypt” or
“decrypt” and applies the Rail Fence Cipher algorithm accordingly. The server expects the
client to send the number of rails (key) and the message to be processed.
•The server then calls the corresponding encryp on or decryp on func on and sends the
result back to the client.
•rail_fence_encrypt(message, rails): Encrypts the message using the Rail Fence Cipher
algorithm.
•rail_fence_decrypt(encrypted_message, rails): Decrypts the message using the Rail Fence
Cipher algorithm by reconstruc ng the zigzag pa ern.
Client Code:
•The client connects to the server and allows the user to choose between encryp on,
decryp on, or qui ng the session.
•The client sends the selected opera on, the key (number of rails), and the message to the
server.
•Upon receiving the result from the server, the client displays the encrypted or decrypted
message.
Summary :
The Rail Fence Cipher is a simple transposi on cipher, which is rela vely easy to break with modern
cryptographic techniques due to its predictable structure. However, it serves as an interes ng
example of a classical cipher used to demonstrate the concept of transposi on encryp on.
ti
ti
ff
ti
ti
fi
ti
ti
ff
fi
ti
ti
tti
ti
ft
tt
tt
tt
ff
tt
ti
ti
ti
ti
ti
tt
tt
ti
ti
tt
ti
ti
ti
ti
ti
ti
tt
ti
tt
ti
ti
ti
ti
ti
ti
ti
tt
ff
Output –