Introduction
In this project, you will learn how to implement the Rail Fence Cipher, a simple encryption method that rearranges the characters in a text to create a ciphertext.
👀 Preview
Thisatext.issample
🎯 Tasks
In this project, you will learn:
- How to set up a Python project directory and create the necessary files
- How to implement the Rail Fence Cipher algorithm in Python
- How to test the implemented encryption function
🏆 Achievements
After completing this project, you will be able to:
- Understand the basic principles of the Rail Fence Cipher
- Implement the Rail Fence Cipher encryption algorithm in Python
- Test and validate the correctness of the implemented encryption function
Implement the Rail Fence Cipher
In this step, you will implement the Rail Fence Cipher encryption algorithm in the fence.py file.
- Open the
fence.pyfile in a text editor. - Add the following code to the file:
def rail_fence_cipher(text: str) -> str:
"""
Encrypts the text using the Rail Fence Cipher method.
Args:
text (str): The text to be encrypted.
Returns:
str: The encrypted text.
"""
if text is None or len(text.strip()) == 0:
return None
group = text.split()
grouped_list = [group[i : i + 2] for i in range(0, len(group), 2)]
first_part = [sublist[0] for sublist in grouped_list]
second_part = [sublist[1] for sublist in grouped_list if len(sublist) > 1]
encryption_text = "".join(first_part + second_part)
return encryption_text
if __name__ == "__main__":
print(rail_fence_cipher("This is a sample text."))
Implement the
rail_fence_cipherfunction by following these steps:- Check if the input
textisNoneor an empty string. If so, returnNone. - Split the
textinto groups of two characters each. - Extract the first character from each group and store them in a list.
- Extract the second character from each group and store them in a list.
- Concatenate the two lists to form the encrypted text.
- Return the encrypted text.
- Check if the input
Save the
fence.pyfile.
Test the Rail Fence Cipher
In this step, you will test the implemented Rail Fence Cipher by running the fence.py file.
- Open a terminal and navigate to the project directory.
- Run the
fence.pyfile:
python3 fence.py
- The output should be the encrypted text:
Thisatext.issample
Congratulations! You have successfully implemented the Rail Fence Cipher in Python.
Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.



