Python/cryptography/playfire.ipynb

361 lines
11 KiB
Plaintext
Raw Normal View History

2024-11-21 04:43:43 +00:00
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "f06af5bc",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<style>.container{width:100%}</style>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%%HTML\n",
"<style>.container{width:100%}</style>"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "b73906e7",
"metadata": {},
"outputs": [],
"source": [
"class PlayFire:\n",
" \"\"\"\n",
2024-11-21 05:08:05 +00:00
" PlayFire class implements the Playfair \n",
" cipher for encryption and decryption of messages.\n",
2024-11-21 04:43:43 +00:00
"\n",
2024-11-21 05:08:05 +00:00
" The Playfair cipher is a digraph substitution \n",
" cipher that encrypts pairs of letters. It requires a key, which\n",
" is used to create a 6x6 matrix of letters and \n",
" digits, and processes the message in pairs.\n",
2024-11-21 04:43:43 +00:00
"\n",
" Attributes:\n",
" key (str): The key used to generate the matrix.\n",
2024-11-21 05:08:05 +00:00
" key_matrix (list): The 6x6 matrix used for \n",
" encryption and decryption.extra (str): The extra character \n",
" used to pad the message if the length is odd (default is 'x').\n",
2024-11-21 04:43:43 +00:00
"\n",
" Methods:\n",
2024-11-21 05:08:05 +00:00
" __verify_key(key): Verifies that the key is \n",
" valid (contains unique characters).\n",
" __make_matrix(): Creates a 6x6 matrix using \n",
" the key and the remaining letters/digits.\n",
" find_idx(pair): Finds the positions (row and column indices) \n",
" of the pair of characters in the matrix.\n",
" encrypt(msg): Encrypts the given message using \n",
" the Playfair cipher.\n",
" decrypt(msg): Decrypts the given encrypted \n",
" message using the Playfair cipher.\n",
2024-11-21 04:43:43 +00:00
" \"\"\"\n",
"\n",
" def __init__(self, key, extra=\"x\"):\n",
" \"\"\"\n",
2024-11-21 05:08:05 +00:00
" Initializes the PlayFire cipher with a key and \n",
" an optional extra character for padding.\n",
2024-11-21 04:43:43 +00:00
"\n",
" Parameters:\n",
" key (str): The key to generate the cipher matrix.\n",
2024-11-21 05:08:05 +00:00
" extra (str, optional): The character used for \n",
" padding the message if its length is odd. Defaults to 'x'.\n",
2024-11-21 04:43:43 +00:00
" \"\"\"\n",
" self.key = self.__verify_key(key)\n",
" self.key_matrix = self.__make_matrix()\n",
" self.extra = extra\n",
"\n",
" def __verify_key(self, key):\n",
" \"\"\"\n",
" Verifies that the provided key contains unique characters.\n",
"\n",
" Parameters:\n",
" key (str): The key to verify.\n",
"\n",
" Returns:\n",
2024-11-21 05:08:05 +00:00
" str: The valid key if it contains only unique \n",
" characters, else prints an error.\n",
2024-11-21 04:43:43 +00:00
" \"\"\"\n",
" keyy = []\n",
" for i in key:\n",
" if i not in keyy:\n",
" keyy.append(i)\n",
" if len(set(key)) == len(key):\n",
" return key\n",
" else:\n",
" print(\"key Error\")\n",
"\n",
" def __make_matrix(self):\n",
" \"\"\"\n",
2024-11-21 05:08:05 +00:00
" Creates a 6x6 matrix from the key by filling \n",
" in remaining characters of the alphabet and digits.\n",
2024-11-21 04:43:43 +00:00
"\n",
" Returns:\n",
" list: A 6x6 matrix for encryption and decryption.\n",
" \"\"\"\n",
" alphanum = list(\"abcdefghijklmnopqrstuvwxyz0123456789\")\n",
" key = list(self.key)\n",
" xx = key + [i for i in alphanum if i not in key]\n",
" mtrx = []\n",
" idx = 0\n",
" for i in range(6):\n",
" t1 = xx[idx : idx + 6]\n",
" mtrx.append(t1)\n",
" idx = idx + 6\n",
" return mtrx\n",
"\n",
" def find_idx(self, pair):\n",
" \"\"\"\n",
2024-11-21 05:08:05 +00:00
" Finds the row and column indices of the \n",
" characters in the matrix.\n",
2024-11-21 04:43:43 +00:00
"\n",
" Parameters:\n",
2024-11-21 05:08:05 +00:00
" pair (list): A pair of characters whose \n",
" positions are to be found in the matrix.\n",
2024-11-21 04:43:43 +00:00
"\n",
" Returns:\n",
2024-11-21 05:08:05 +00:00
" list: A list containing the row and column \n",
" indices of both characters in the matrix.\n",
2024-11-21 04:43:43 +00:00
" \"\"\"\n",
" idxs = [6, 6]\n",
" for i in range(6):\n",
" for j in range(6):\n",
" if i == 5:\n",
" i = -1\n",
" if j == 5:\n",
" j = -1\n",
" if pair[0] == self.key_matrix[i][j]:\n",
" idxs[0] = [i, j]\n",
" if pair[1] == self.key_matrix[i][j]:\n",
" idxs[1] = [i, j]\n",
" return idxs\n",
"\n",
" def encrypt(self, msg: str):\n",
" \"\"\"\n",
" Encrypts the given message using the Playfair cipher.\n",
"\n",
" Parameters:\n",
" msg (str): The plaintext message to encrypt.\n",
"\n",
" Returns:\n",
" str: The encrypted message.\n",
" \"\"\"\n",
" msg = list(msg.lower())\n",
" if len(msg) % 2 == 1:\n",
" msg.append(self.extra)\n",
" pairs = []\n",
" for i in range(0, len(msg), 2):\n",
" pairs.append(msg[i : i + 2])\n",
" en_msg = \"\"\n",
" for i in pairs:\n",
" idxs = self.find_idx(i)\n",
" if idxs[0][0] == idxs[1][0]:\n",
" en_m = (\n",
" self.key_matrix[idxs[0][0]][idxs[0][1] + 1]\n",
" + self.key_matrix[idxs[0][0]][idxs[1][1] + 1]\n",
" )\n",
" elif idxs[0][1] == idxs[1][1]:\n",
" en_m = (\n",
" self.key_matrix[idxs[0][0] + 1][idxs[0][1]]\n",
" + self.key_matrix[idxs[1][0] + 1][idxs[1][1]]\n",
" )\n",
" else:\n",
" en_m = (\n",
" self.key_matrix[idxs[0][0]][idxs[1][1]]\n",
" + self.key_matrix[idxs[1][0]][idxs[0][1]]\n",
" )\n",
" en_msg += en_m\n",
" return en_msg\n",
"\n",
" def decrypt(self, msg):\n",
" \"\"\"\n",
" Decrypts the given encrypted message using the Playfair cipher.\n",
"\n",
" Parameters:\n",
" msg (str): The encrypted message to decrypt.\n",
"\n",
" Returns:\n",
" str: The decrypted plaintext message.\n",
" \"\"\"\n",
" msg = list(msg.lower())\n",
" if len(msg) % 2 == 1:\n",
" msg.append(self.extra)\n",
" pairs = []\n",
" for i in range(0, len(msg), 2):\n",
" pairs.append(msg[i : i + 2])\n",
" en_msg = \"\"\n",
" for i in pairs:\n",
" idxs = self.find_idx(i)\n",
" if idxs[0][0] == idxs[1][0]:\n",
" en_m = (\n",
" self.key_matrix[idxs[0][0]][idxs[0][1] - 1]\n",
" + self.key_matrix[idxs[0][0]][idxs[1][1] - 1]\n",
" )\n",
" elif idxs[0][1] == idxs[1][1]:\n",
" en_m = (\n",
" self.key_matrix[idxs[0][0] - 1][idxs[0][1]]\n",
" + self.key_matrix[idxs[1][0] - 1][idxs[1][1]]\n",
" )\n",
" else:\n",
" en_m = (\n",
" self.key_matrix[idxs[0][0]][idxs[1][1]]\n",
" + self.key_matrix[idxs[1][0]][idxs[0][1]]\n",
" )\n",
" en_msg += en_m\n",
" return en_msg"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "4b861600",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[['m', 'o', 'n', 'a', 'r', 'c'],\n",
" ['h', 'y', '1', '2', '3', 'b'],\n",
" ['d', 'e', 'f', 'g', 'i', 'j'],\n",
" ['k', 'l', 'p', 'q', 's', 't'],\n",
" ['u', 'v', 'w', 'x', 'z', '0'],\n",
" ['4', '5', '6', '7', '8', '9']]"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pf = PlayFire(key=\"monarchy123\")\n",
"pf.key_matrix"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "7c4e1caa",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'ydppny3b7u'"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"msg = \"hello1234\"\n",
"enc = pf.encrypt(msg)\n",
"enc"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "48c8a847",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'hello1234x'"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pf.decrypt(enc)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "62806ee1",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'thismy1stdayofcollegeilearntabouteverythingandmetmyfriends'"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pf.decrypt(pf.encrypt(\"thismy1stdayofcollegeilearntabouteverythingandmetmyfriends\"))"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "a7a9907b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'rx'"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pf.decrypt(pf.encrypt(\"r\"))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6fe9dad9",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}