cryptography

This commit is contained in:
Bibekananda Hati 2024-11-20 22:52:43 +05:30
parent d6aa4403d9
commit 27332fa728
7 changed files with 1249 additions and 4 deletions

View File

@ -39,9 +39,7 @@
"cell_type": "code",
"execution_count": 52,
"id": "1a17a18b",
"metadata": {
"scrolled": false
},
"metadata": {},
"outputs": [
{
"data": {
@ -812,7 +810,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
"version": "3.12.3"
}
},
"nbformat": 4,

View File

@ -0,0 +1,158 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "1057a613",
"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": "markdown",
"id": "040e1454",
"metadata": {},
"source": [
"## Key generation for DES for 16 rounds"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "7bd02a30",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['1B02EFFC7072',\n",
" '79AED9DBC9E5',\n",
" '55FC8A42CF99',\n",
" '72ADD6DB351D',\n",
" '7CEC07EB53A8',\n",
" '63A53E507B2F',\n",
" 'EC84B7F618BC',\n",
" 'F78A3AC13BFB',\n",
" 'E0DBEBEDE781',\n",
" 'B1F347BA464F',\n",
" '215FD3DED386',\n",
" '7571F59467E9',\n",
" '97C5D1FABA41',\n",
" '5F43B7F2E73A',\n",
" 'BF918D3D3F0A',\n",
" 'CB3D8B0E17F5']"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import random\n",
"def r64():\n",
" r64 = ''\n",
" for i in range(8):\n",
" r = str(bin(random.randint(0,2**8)))[2:]\n",
" if(len(r)<8):\n",
" r = '0'*(8-len(r)) + r\n",
" r64 +=r\n",
" return r64\n",
"def hex2bin(hexa):\n",
" binstr = bin(int(hexa,16))[2:]\n",
" binstr = binstr.zfill(len(hexa)*4)\n",
" return binstr\n",
"\n",
"def bin2hex(binary):\n",
" binary = binary.zfill(len(binary) +( 4-len(binary)%4)%4)\n",
" hexa = hex(int(binary,2))[2:].upper()\n",
" return hexa\n",
"\n",
"\n",
"def key_gen(bit64):\n",
" bit64 = '#'+bit64\n",
" PC_1 = [57,49,41,33, 25,17,9,1,\n",
" 58,50,42,34, 26,18,10, \n",
" 2,59,51,43, 35,27,19,11,\n",
" 3,60,52,44, 36,63,55,47,\n",
" 39,31,23,15, 7,62,54,46,\n",
" 38,30,22,14, 6,61,53,45,\n",
" 37,29,21,13, 5,28,20,12,4]\n",
" \n",
" PC_2 = [14,17,11,24, 1,5,3,28,\n",
" 15,6,21,10, 23,19,12,4,\n",
" 26,8,16,7, 27,20,13,2, 41,52,31,37, 47,55,30,40,51,45,33,48, 44,49,39,56,34,53,46,42, 50,36,29,32]\n",
" bit56 = ''\n",
" for i in PC_1:\n",
" bit56 +=bit64[i]\n",
" L,R = bit56[:28],bit56[28:]\n",
" round_keys = []\n",
" ones = [1,2,9,16]\n",
" for i in range(1,17):\n",
" if(i in ones):\n",
" l = L[1:]+L[:1]\n",
" r = R[1:]+R[:1]\n",
" else:\n",
" l = L[2:]+L[:2]\n",
" r = R[2:]+R[:2]\n",
" k = '#'+l+r\n",
" sub_key = ''\n",
" for i in PC_2:\n",
" sub_key += k[i]\n",
" L,R = l,r\n",
"# print(len(k),len(sub_key))\n",
" round_keys.append(sub_key)\n",
" return round_keys\n",
"\n",
"test = \"133457799BBCDFF1\"\n",
"subkeys = key_gen(hex2bin(test))\n",
"[bin2hex(i) for i in subkeys]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "64b7d8da",
"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
}

View File

@ -0,0 +1,173 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "8561e0a7",
"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": 2,
"id": "12f36b2f",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"21"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def eucld_gcd(a,b):\n",
" if(a < b):\n",
" a , b = b , a\n",
" if(b==0):\n",
" return a\n",
" r = a%b\n",
" if(r==0):\n",
" return b\n",
" return eucld_gcd(b,r)\n",
"eucld_gcd(252,105)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "c060ee17",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, -48]"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import numpy as np\n",
"def ext_eucld(a,b):\n",
" swap = False\n",
" if(a < b):\n",
" a , b = b , a\n",
" swap = True\n",
" def eucld(a,b):\n",
" if(b==0 or b==1):\n",
" return []\n",
" ls = []\n",
" while b!=1:\n",
" r = a%b\n",
" if(r==0):\n",
" return ls\n",
" idx = (a-r)//b\n",
" ls.append(idx)\n",
" a = b\n",
" b = r\n",
" return ls\n",
" \n",
" row = np.array([[1,0],[0,1]])\n",
" ls = eucld(a,b)\n",
" for i in ls:\n",
" row = np.append(row, [row[-2] - i*row[-1]] ,axis=0)\n",
" if(swap):\n",
" return list(row[-1])[::-1]\n",
" return list(row[-1])\n",
"ext_eucld(97,2)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "d3edd1f6",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a=5, b=7, gcd=1, m=3, n=-2, ma+nb=1\n"
]
}
],
"source": [
"a = 5\n",
"b = 7\n",
"gcd = eucld_gcd(a,b)\n",
"m,n = ext_eucld(a,b)\n",
"print(f\"a={a}, b={b}, gcd={gcd}, m={m}, n={n}, ma+nb={m*a+n*b}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "782bb8d3",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "e224063e",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "63f1d5a4",
"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
}

View File

@ -0,0 +1,415 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "054915e4",
"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": 2,
"id": "62243eff",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[0, 0, 0, 0, 1, 1, 0, 1]"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def id2bit(ls:list):\n",
" if(len(ls)==0):\n",
" return [0,0,0,0, 0,0,0,0]\n",
" aa = [0 for i in range(max(ls)+1)]\n",
" for i in ls:\n",
" aa[i]=1\n",
" return aa[::-1]\n",
"def bit2id(ls:list,log=False):\n",
" ls = ls[::-1]\n",
" aa =[]\n",
" \n",
" for i in range(len(ls)):\n",
" if(ls[i]==1):\n",
" aa.append(i)\n",
" return aa[::-1]\n",
"\n",
"def bit2mul(a,b,log=False):\n",
" \n",
" ai = bit2id(a)\n",
" bi = bit2id(b)\n",
" a,b = a[::-1],b[::-1]\n",
" \n",
" if(ai==[]):\n",
" return a\n",
" elif(bi==[]):\n",
" return b\n",
" \n",
" addn = [ [ ai[i]+bi[j] for j in range(len(bi)) ][::-1] for i in range(len(ai)) ][::-1]\n",
" addn = [id2bit(i) for i in addn]\n",
" \n",
" maxsiz = max([len(i) for i in addn])\n",
" for i in range(len(addn)):\n",
" if(len(addn[i])<maxsiz):\n",
" addn[i] = [0 for j in range(maxsiz-len(addn[i]))]+addn[i]\n",
" smm=[]\n",
" for i in range(maxsiz):\n",
" t= 0\n",
" for j in addn:\n",
" t += j[i]\n",
" smm.append(t%2)\n",
" return smm\n",
"\n",
"def bit2add(a,b):\n",
" a,b = list(a),list(b)\n",
" a,b=a[::-1],b[::-1]\n",
" maxsiz=max(len(a),len(b))\n",
" \n",
" \n",
" if(len(a)<maxsiz):\n",
" a = a+[0 for j in range(maxsiz-len(a))]\n",
" if(len(b)<maxsiz):\n",
" b = b+[0 for j in range(maxsiz-len(b))]\n",
" smm=[]\n",
" for i in range(maxsiz):\n",
" smm.append((a[i]+b[i])%2)\n",
" return smm[::-1]\n",
"def bit2str(bit:list):\n",
" s = \"\"\n",
" for i in bit:\n",
" s+=str(i)\n",
" return s\n",
"def str2bit(s:str):\n",
" if(set(s).issubset(set('01'))):\n",
" bit=[]\n",
" for i in s:\n",
" bit.append(int(i))\n",
" return bit\n",
" else:\n",
" print(\"bit string should contain 1s and 0s\")\n",
"def modgf(dsr:list,dnt = [1, 0, 0, 0, 1, 1, 0, 1, 1]):\n",
" dsr = bit2id(dsr)\n",
" dnt = bit2id(dnt)\n",
" qtnt = []\n",
" while (len(dnt)!=0 and len(dsr)!=0 and (max(dnt)-max(dsr)>=0)):\n",
" ml = max(dnt)-max(dsr)\n",
" qtnt.append(ml)\n",
" plus = id2bit(dnt)\n",
" minus = id2bit([ml+i for i in dsr])\n",
" rem = bit2add(plus,minus)\n",
" dnt = bit2id(rem)\n",
" return id2bit(dnt),id2bit(qtnt)\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"# import numpy as np\n",
"def ext_eucld(a,b,log=False):\n",
" ai,bi = bit2id(a),bit2id(b)\n",
" if((len(ai)!=0 and len(bi)!=0)):\n",
" if(max(max(ai),max(bi))==max(bi)):\n",
" a,b=b,a\n",
" elif(len(ai)==0 and len(bi)!=0):\n",
" a,b=b,a\n",
" def eucld(a,b,log=False):\n",
" \n",
" a,b = a[::-1],b[::-1]\n",
" if(set(b)==set([0]) or (b[0]==1 and (set(b[1:])==set([0])))):\n",
" return []\n",
" ls = []\n",
" \n",
" while not (b[0]==1 and (set(b[1:])==set([0]))):\n",
" \n",
" r,idx = modgf(b[::-1],dnt=a[::-1])\n",
" r,idx = r[::-1],idx[::-1]\n",
" \n",
" if(set(r)==set([0])):\n",
" return ls\n",
" \n",
" ls.append(idx[::-1])\n",
" a = b\n",
" b = r\n",
" return ls\n",
" \n",
" row = [[[0,0,0,0, 0,0,0,1],[0,0,0,0, 0,0,0,0]],\n",
" [[0,0,0,0, 0,0,0,0],[0,0,0,0, 0,0,0,1]]]\n",
" ls = eucld(a,b)\n",
" for i in ls:\n",
" r10,r11 = row[-1][0], row[-1][1]\n",
" r20,r21 = row[-2][0], row[-2][1]\n",
" r0 = bit2add(r20,bit2mul(r10,i))\n",
" r1 = bit2add(r21,bit2mul(r11,i))\n",
" rowl = [r0,r1]\n",
" row.append(rowl)\n",
" return row[-1]\n",
"def Gfinv(bit,irrpoly = [1, 0, 0, 0, 1, 1, 0, 1, 1]):\n",
" if(set(bit)==set('0')):\n",
" return '--'\n",
" ans = ext_eucld(irrpoly,bit)\n",
" ans = ans[-1][-len(bit):]\n",
" return ans\n",
"\n",
"\n",
"Gfinv([0,0,0,0,0,1,0,0],irrpoly=[0,0,0,1, 0,0,1,1])"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2b8ce266",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "38ba4051",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "0c2b9aab",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "9410bfdf",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 3,
"id": "edb53805",
"metadata": {},
"outputs": [],
"source": [
"def genmapping(n:int,irrpoly):\n",
" gf = [str(bin(i))[2:] for i in range(2**n)]\n",
" for i in range(len(gf)):\n",
" if(len(gf[i])<n):\n",
" gf[i] = '0'*(n-len(gf[i])) + gf[i]\n",
" key2ele = dict(enumerate(gf))\n",
" ele2key = dict([i[::-1] for i in list(enumerate(gf))])\n",
" invmap = dict()\n",
" for i in gf:\n",
" if(set(i)!=set('0')):\n",
" inv = bit2str(Gfinv(str2bit(i),irrpoly=irrpoly))\n",
" invmap[ele2key[i]] = ele2key[inv]\n",
" return gf,invmap"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "d4ca99d5",
"metadata": {},
"outputs": [],
"source": [
"gf5,invmap = genmapping(n=5,irrpoly=id2bit([5,2,0]))"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "44e4797e",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"set(invmap.values())==set(invmap.keys())"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "b08bd2b6",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{1: 1,\n",
" 2: 18,\n",
" 3: 28,\n",
" 4: 9,\n",
" 5: 23,\n",
" 6: 14,\n",
" 7: 12,\n",
" 8: 22,\n",
" 9: 4,\n",
" 10: 25,\n",
" 11: 16,\n",
" 12: 7,\n",
" 13: 15,\n",
" 14: 6,\n",
" 15: 13,\n",
" 16: 11,\n",
" 17: 24,\n",
" 18: 2,\n",
" 19: 29,\n",
" 20: 30,\n",
" 21: 26,\n",
" 22: 8,\n",
" 23: 5,\n",
" 24: 17,\n",
" 25: 10,\n",
" 26: 21,\n",
" 27: 31,\n",
" 28: 3,\n",
" 29: 19,\n",
" 30: 20,\n",
" 31: 27}"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"invmap"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "90374ee9",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 9,
"id": "06a7f472",
"metadata": {},
"outputs": [],
"source": [
"gf28 = [str(bin(i))[2:] for i in range(256)]\n",
"for i in range(len(gf28)):\n",
" if(len(gf28[i])<8):\n",
" gf28[i] = '0'*(8-len(gf28[i])) + gf28[i]\n",
"\n",
"key2ele = dict(enumerate(gf28))\n",
"ele2key = dict([i[::-1] for i in list(enumerate(gf28))])\n",
"invmap = dict()\n",
"for i in gf28:\n",
"\n",
" if(set(i)!=set('0')):\n",
" inv = bit2str(Gfinv(str2bit(i)))\n",
" invmap[ele2key[i]] = ele2key[inv]"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "5fcfedd5",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"set(invmap.values())==set(invmap.keys())"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4059dff6",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "06b3e5d5",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "37dd903a",
"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
}

View File

@ -0,0 +1,245 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "65571230-ccb3-41a1-a361-31097b31bc5b",
"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": 2,
"id": "f12511c2-01b6-45f4-b6b6-1bfe1dc93631",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 0, 0, 0, 0, 1, 0, 1, 1, 0]"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def id2bit(ls:list):\n",
" if(len(ls)==0):\n",
" return [0,0,0,0, 0,0,0,0] # Return a default 8-bit array\n",
" aa = [0 for i in range(max(ls)+1)]\n",
" for i in ls:\n",
" aa[i] = 1\n",
" return aa[::-1]\n",
"\n",
"def bit2id(ls:list):\n",
" ls = ls[::-1]\n",
" aa = []\n",
" for i in range(len(ls)):\n",
" if(ls[i] == 1):\n",
" aa.append(i)\n",
" return aa[::-1]\n",
" \n",
"def XOR(*args):\n",
" result = 0\n",
" for arg in args:\n",
" result ^= arg\n",
" return result\n",
" \n",
"class LFSR:\n",
" def __init__(self,start,poly):\n",
" self.seq = start\n",
" self.taps = bit2id(poly[:-1]) # ignore the output tap (final bit)\n",
"\n",
" if len(self.seq) != len(poly) - 1:\n",
" raise ValueError(\"Polynomial and start value length mismatch\")\n",
"\n",
" def clock(self):\n",
" # print(self.seq) \n",
" feedback = XOR(*[self.seq[bit] for bit in self.taps])\n",
" \n",
" self.seq = [feedback] + self.seq[:-1]\n",
"\n",
" \n",
"class A51:\n",
" def __init__(self,lfsrs,clock_bits):\n",
" self.lfsrs = lfsrs\n",
" self.clock_bits = clock_bits\n",
" self.lfsr_count = len(clock_bits)\n",
" def majority(self, *bits):\n",
" ones = sum(i for i in bits if i==1)\n",
" if ones >= self.lfsr_count / 2:\n",
" majority_bit = 1\n",
" else:\n",
" majority_bit = 0\n",
" return majority_bit\n",
" \n",
" def clock(self):\n",
" majority = self.majority(*[self.lfsrs[i].seq[self.clock_bits[i]] for i in range(self.lfsr_count)])\n",
" for i in range(self.lfsr_count):\n",
" if(self.lfsrs[i].seq[self.clock_bits[i]] == majority):\n",
" self.lfsrs[i].clock()\n",
" out = XOR(*[int(i.seq[-1]) for i in self.lfsrs])\n",
" return out\n",
" \n",
"lf1 = LFSR(start=[1,0,1,1],poly=id2bit([4,1]))\n",
"lf2 = LFSR(start=[0,1,1,1],poly=id2bit([4,1]))\n",
"lf3 = LFSR(start=[1,0,1,0],poly=id2bit([4,1]))\n",
"a51 = A51(lfsrs=[lf1,lf2,lf3],clock_bits=[1,2,0])\n",
"stream = [a51.clock() for i in range(10)]\n",
"stream"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "182b2a83-d083-4296-a3bc-4d4f14dd8724",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"def write2txt_file(bitstream, filename):\n",
" \"\"\"Writes a bitstream (string of '0's and '1's) to a text file.\"\"\"\n",
" with open(filename, 'a') as f: # Open in append mode to continue writing\n",
" f.write(bitstream)\n",
"\n",
"def write2bin_file(bitstream, filename):\n",
" byte_list = []\n",
" \n",
" # Pad the bitstream if it's not a multiple of 8\n",
" padding = (8 - (len(bitstream) % 8)) % 8\n",
" bitstream += '0' * padding # Add extra '0's to make the length a multiple of 8\n",
" \n",
" for i in range(0, len(bitstream), 8):\n",
" byte = bitstream[i:i+8]\n",
" byte_list.append(int(byte, 2)) # Convert 8 bits to an integer (byte)\n",
" \n",
" # Append the bytes to the binary file\n",
" with open(filename, 'ab') as f: # 'ab' mode to append to the binary file\n",
" f.write(bytearray(byte_list))\n",
"\n",
"def gen_bit_stream(data:dict,target_size,file_path):\n",
" lfsrs = [LFSR(start=i[\"start\"],poly=i[\"poly\"]) for i in data]\n",
" a51 = A51(lfsrs=lfsrs,clock_bits=[i[\"clock\"] for i in data])\n",
" \n",
" # filename = 'bitstream_output_1GB.bin'\n",
" # target_size = 1 * 1024 * 1024 * 1024 # 1 GB in bytes\n",
" current_size = 0\n",
"\n",
" bitstream_chunk = \"\" # Chunk of bits to write periodically\n",
" chunk_size = 10000 # Number of bits to generate at a time (can adjust for performance)\n",
" progress_interval = target_size // 10 # 1/10th of the target size (100 MB)\n",
" next_progress_checkpoint = progress_interval\n",
" \n",
" while current_size < target_size:\n",
" # Generate bits in chunks\n",
" for _ in range(chunk_size):\n",
" bitstream_chunk += str(a51.clock())\n",
"\n",
" # Write chunk to file\n",
" # write2bin_file(bitstream_chunk, filename)\n",
" write2txt_file(bitstream_chunk, file_path)\n",
" \n",
" # Clear the chunk and update the current file size\n",
" bitstream_chunk = \"\"\n",
" current_size = os.path.getsize(file_path)\n",
" # Check if the file size has crossed the 1/10th checkpoint\n",
" if current_size >= next_progress_checkpoint:\n",
" print(f\"File size crossed {round(next_progress_checkpoint / (1024 * 1024),2)} MB\")\n",
" next_progress_checkpoint += progress_interval # Update to next 10% checkpoint\n",
"\n",
" \n",
"\n",
" print(f\"File generation complete: {file_path} (target)\")"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "ebf2b473-4277-4b99-9935-96802dc52488",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"File size crossed 0.1 MB\n",
"File size crossed 0.2 MB\n",
"File size crossed 0.3 MB\n",
"File size crossed 0.4 MB\n",
"File size crossed 0.5 MB\n",
"File size crossed 0.6 MB\n",
"File size crossed 0.7 MB\n",
"File size crossed 0.8 MB\n",
"File size crossed 0.9 MB\n",
"File size crossed 1.0 MB\n",
"File generation complete: mine_gen_100MB.txt (target)\n"
]
}
],
"source": [
"data = [\n",
" {\"start\": [0, 1, 0, 1, 1], \"poly\": id2bit([5, 2, 0]), \"clock\": 2},\n",
" {\"start\": [1, 0, 0, 1, 0], \"poly\": id2bit([5, 4, 3, 1, 0]), \"clock\": 3},\n",
" {\"start\": [0, 1, 1, 0, 0], \"poly\": id2bit([5, 4, 2, 1, 0]), \"clock\": 2}\n",
"]\n",
"gen_bit_stream(data, target_size=1*1024**2, file_path=\"mine_gen_100MB.txt\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "80acd699-63bc-4391-ac05-8166a843b1ca",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "01038d4c-ab7f-486c-b300-a95187f4cd76",
"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
}

File diff suppressed because one or more lines are too long

255
cryptography/playfire.ipynb Normal file
View File

@ -0,0 +1,255 @@
{
"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": 4,
"id": "b73906e7",
"metadata": {},
"outputs": [],
"source": [
"class PlayFire:\n",
" def __init__(self,key,extra='x'):\n",
" self.key = self.__verify_key(key)\n",
" self.key_matrix = self.__make_matrix()\n",
" self.extra = extra\n",
" def __verify_key(self,key):\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",
" def __make_matrix(self):\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",
" def find_idx(self,pair):\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",
" def encrypt(self,msg:str):\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 = self.key_matrix[idxs[0][0]][idxs[0][1]+1]+self.key_matrix[idxs[0][0]][idxs[1][1]+1]\n",
" elif(idxs[0][1]==idxs[1][1]):\n",
" \n",
" en_m = self.key_matrix[idxs[0][0]+1][idxs[0][1]]+self.key_matrix[idxs[1][0]+1][idxs[1][1]]\n",
" else:\n",
" en_m = self.key_matrix[idxs[0][0]][idxs[1][1]]+self.key_matrix[idxs[1][0]][idxs[0][1]]\n",
" en_msg += en_m\n",
" return en_msg\n",
" \n",
" def decrypt(self,msg):\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 = self.key_matrix[idxs[0][0]][idxs[0][1]-1]+self.key_matrix[idxs[0][0]][idxs[1][1]-1]\n",
" elif(idxs[0][1]==idxs[1][1]):\n",
" en_m = self.key_matrix[idxs[0][0]-1][idxs[0][1]]+self.key_matrix[idxs[1][0]-1][idxs[1][1]]\n",
" else:\n",
" en_m = self.key_matrix[idxs[0][0]][idxs[1][1]]+self.key_matrix[idxs[1][0]][idxs[0][1]]\n",
" en_msg += en_m\n",
" return en_msg"
]
},
{
"cell_type": "code",
"execution_count": 5,
"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": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pf = PlayFire(key=\"monarchy123\")\n",
"pf.key_matrix"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "7c4e1caa",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'ydppny3b7u'"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"msg = 'hello1234'\n",
"enc = pf.encrypt(msg)\n",
"enc"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "48c8a847",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'hello1234x'"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pf.decrypt(enc)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "62806ee1",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'thismy1stdayofcollegeilearntabouteverythingandmetmyfriends'"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pf.decrypt(pf.encrypt(\"thismy1stdayofcollegeilearntabouteverythingandmetmyfriends\"))"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "a7a9907b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'rx'"
]
},
"execution_count": 9,
"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
}