├── .gitignore
├── Classic ciphers.ipynb
├── DHKE.ipynb
├── DSA.ipynb
├── Elliptic Curves.ipynb
├── Hash Functions.ipynb
├── Information-Theoretic Security.ipynb
├── LICENSE
├── README.md
├── RSA.ipynb
├── Secret Sharing (gf).ipynb
├── Secret Sharing.ipynb
├── StreamCiphers.ipynb
├── Symmetric.ipynb
├── cat.txt
├── encrypted_cat.txt
├── requirements.txt
├── tux.png
└── tux_gray.png
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 | MANIFEST
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 | .pytest_cache/
49 |
50 | # Translations
51 | *.mo
52 | *.pot
53 |
54 | # Django stuff:
55 | *.log
56 | local_settings.py
57 | db.sqlite3
58 |
59 | # Flask stuff:
60 | instance/
61 | .webassets-cache
62 |
63 | # Scrapy stuff:
64 | .scrapy
65 |
66 | # Sphinx documentation
67 | docs/_build/
68 |
69 | # PyBuilder
70 | target/
71 |
72 | # Jupyter Notebook
73 | .ipynb_checkpoints
74 |
75 | # pyenv
76 | .python-version
77 |
78 | # celery beat schedule file
79 | celerybeat-schedule
80 |
81 | # SageMath parsed files
82 | *.sage.py
83 |
84 | # Environments
85 | .env
86 | .venv
87 | env/
88 | venv/
89 | ENV/
90 | env.bak/
91 | venv.bak/
92 |
93 | # Spyder project settings
94 | .spyderproject
95 | .spyproject
96 |
97 | # Rope project settings
98 | .ropeproject
99 |
100 | # mkdocs documentation
101 | /site
102 |
103 | # mypy
104 | .mypy_cache/
105 |
106 | secret_notebooks/
107 | progetti/
108 |
109 | .vagrant*
--------------------------------------------------------------------------------
/Classic ciphers.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "slideshow": {
7 | "slide_type": "slide"
8 | }
9 | },
10 | "source": [
11 | "## The Shift Cipher"
12 | ]
13 | },
14 | {
15 | "cell_type": "markdown",
16 | "metadata": {},
17 | "source": [
18 | "The shift cipher is one of the oldest encryption schemes also used by Caesar, who\n",
19 | "> wrote it in cipher, that is, by so changing the order of the letters of the alphabet, that not a word could be made out. If anyone wishes to decipher these, and get at their meaning, he must substitute the fourth letter of the alphabet, namely D, for A, and so with the others. (Suetonius)"
20 | ]
21 | },
22 | {
23 | "cell_type": "markdown",
24 | "metadata": {},
25 | "source": [
26 | "Messages are strings of any size of uppercase letters.\n",
27 | "\n",
28 | "Let’s encode each letter as A=0,B=1, …,Z=25.\n",
29 | "\n",
30 | "The key is any integer $0 \\leq k \\leq 25$."
31 | ]
32 | },
33 | {
34 | "cell_type": "code",
35 | "execution_count": null,
36 | "metadata": {},
37 | "outputs": [],
38 | "source": [
39 | "import math\n",
40 | "import collections\n",
41 | "import matplotlib.pyplot as plt\n",
42 | "from sympy.crypto.crypto import AZ\n",
43 | "from sympy.crypto.crypto import encipher_shift, decipher_shift\n",
44 | "from sympy.crypto.crypto import encipher_vigenere, decipher_vigenere"
45 | ]
46 | },
47 | {
48 | "cell_type": "code",
49 | "execution_count": null,
50 | "metadata": {},
51 | "outputs": [],
52 | "source": [
53 | "# Let's define a ciphertext using the letters of the alphabet\n",
54 | "\n",
55 | "m = AZ(\"Go Navy! Beat Army!\")\n",
56 | "m"
57 | ]
58 | },
59 | {
60 | "cell_type": "code",
61 | "execution_count": null,
62 | "metadata": {},
63 | "outputs": [],
64 | "source": [
65 | "# encrypt with k = 1\n",
66 | "k = 1\n",
67 | "c = encipher_shift(m, k)\n",
68 | "c"
69 | ]
70 | },
71 | {
72 | "cell_type": "code",
73 | "execution_count": null,
74 | "metadata": {
75 | "slideshow": {
76 | "slide_type": "-"
77 | }
78 | },
79 | "outputs": [],
80 | "source": [
81 | "# now decrypt\n",
82 | "decipher_shift(c,k)"
83 | ]
84 | },
85 | {
86 | "cell_type": "code",
87 | "execution_count": null,
88 | "metadata": {
89 | "slideshow": {
90 | "slide_type": "slide"
91 | }
92 | },
93 | "outputs": [],
94 | "source": [
95 | "# Now a bit more complicated\n",
96 | "# Let's find the decryption of a ciphertext\n",
97 | "c = AZ(\"LRZZOACZZQTDZYPESLEXLVPDFDHTDPC\")\n",
98 | "\n",
99 | "# We try all the keys\n",
100 | "for i in range(26):\n",
101 | "\t\tprint(i, decipher_shift(c, i))"
102 | ]
103 | },
104 | {
105 | "cell_type": "code",
106 | "execution_count": null,
107 | "metadata": {
108 | "slideshow": {
109 | "slide_type": "slide"
110 | }
111 | },
112 | "outputs": [],
113 | "source": [
114 | "# k = 11 makes sense\n",
115 | "k = 11\n",
116 | "decipher_shift(c, k)"
117 | ]
118 | },
119 | {
120 | "cell_type": "code",
121 | "execution_count": null,
122 | "metadata": {},
123 | "outputs": [],
124 | "source": [
125 | "# Can we make it automatic?\n",
126 | "# Let's use a longer text\n",
127 | "raven = \"\"\"Once upon a midnight dreary, while I pondered, weak and weary, \n",
128 | " Over many a quaint and curious volume of forgotten lore, \n",
129 | " While I nodded, nearly napping, suddenly there came a tapping,\n",
130 | " As of some one gently rapping, rapping at my chamber door.\n",
131 | " Tis some visiter, I muttered, tapping at my chamber door --\n",
132 | " Only this,and nothing more.\"\"\"\n",
133 | "m = AZ(raven)\n",
134 | "freq = collections.Counter(m)\n",
135 | "plt.bar(freq.keys(),freq.values());"
136 | ]
137 | },
138 | {
139 | "cell_type": "markdown",
140 | "metadata": {},
141 | "source": [
142 | "# Entropy\n",
143 | "Given a letter $m$ taken from a set of letter $\\{m_1, \\dots, m_N\\}$ with probabilities $p(m_i)\\ 1\\leq i \\leq N$, the source entropy is\n",
144 | "\n",
145 | "$H(m) = -\\sum_{i=1}^N p_i \\log_2 p_i$\n",
146 | "\n",
147 | "Source entropy is a measure of how much a source's messages are uniformly distributed."
148 | ]
149 | },
150 | {
151 | "cell_type": "code",
152 | "execution_count": null,
153 | "metadata": {},
154 | "outputs": [],
155 | "source": [
156 | "# Calculate entropy given the histogram\n",
157 | "def entropy(p):\n",
158 | " # normalization constant (probability must sum to 1)\n",
159 | " norm = sum(p)\n",
160 | " # definition of entropy\n",
161 | " return -sum([ pi/norm*math.log2(pi/norm) for pi in p ])"
162 | ]
163 | },
164 | {
165 | "cell_type": "code",
166 | "execution_count": null,
167 | "metadata": {
168 | "slideshow": {
169 | "slide_type": "slide"
170 | }
171 | },
172 | "outputs": [],
173 | "source": [
174 | "# Calculate and plot the frequencies of letters in a message\n",
175 | "def plot_frequencies(msg):\n",
176 | " freq = collections.Counter(msg)\n",
177 | " plt.bar(freq.keys(),freq.values())\n",
178 | " plt.title(\"Entropy: {} bits\".format(entropy(freq.values())))\n",
179 | " plt.show()"
180 | ]
181 | },
182 | {
183 | "cell_type": "code",
184 | "execution_count": null,
185 | "metadata": {
186 | "slideshow": {
187 | "slide_type": "slide"
188 | }
189 | },
190 | "outputs": [],
191 | "source": [
192 | "# Show the letter frequencies in the plaintext\n",
193 | "# Letter E is the most common\n",
194 | "plot_frequencies(m)"
195 | ]
196 | },
197 | {
198 | "cell_type": "code",
199 | "execution_count": null,
200 | "metadata": {
201 | "slideshow": {
202 | "slide_type": "slide"
203 | }
204 | },
205 | "outputs": [],
206 | "source": [
207 | "# Let's decrypt a longer message using frequency analysis\n",
208 | "ciphertext = \"\"\"VUJLBWVUHTPKUPNOAKYLHYFDOPSLPWVUK\n",
209 | " LYLKDLHRHUKDLHYFVCLYTHUFHXBHPUAHU\n",
210 | " KJBYPVBZCVSBTLVMMVYNVAALUSVYLDOPS\n",
211 | " LPUVKKLKULHYSFUHWWPUNZBKKLUSFAOLY\n",
212 | " LJHTLHAHWWPUNHZVMZVTLVULNLUASFYHW\n",
213 | " WPUNYHWWPUNHATFJOHTILYKVVYAPZZVTL\n",
214 | " CPZPALYPTBAALYLKAHWWPUNHATFJOHTIL\n",
215 | " YKVVYVUSFAOPZHUKUVAOPUNTVY\"\"\"\n",
216 | "c = AZ(ciphertext)\n",
217 | "plot_frequencies(c)"
218 | ]
219 | },
220 | {
221 | "cell_type": "code",
222 | "execution_count": null,
223 | "metadata": {
224 | "slideshow": {
225 | "slide_type": "slide"
226 | }
227 | },
228 | "outputs": [],
229 | "source": [
230 | "# A shift cipher does not change the shape of the histogram and neither its entropy\n",
231 | "\n",
232 | "# Maybe E is encrypted to L?\n",
233 | "# We calculate the shift\n",
234 | "shift = ord(\"L\")- ord(\"E\")\n",
235 | "shift"
236 | ]
237 | },
238 | {
239 | "cell_type": "code",
240 | "execution_count": null,
241 | "metadata": {
242 | "slideshow": {
243 | "slide_type": "-"
244 | }
245 | },
246 | "outputs": [],
247 | "source": [
248 | "decipher_shift(c, 7)"
249 | ]
250 | },
251 | {
252 | "cell_type": "code",
253 | "execution_count": null,
254 | "metadata": {
255 | "slideshow": {
256 | "slide_type": "-"
257 | }
258 | },
259 | "outputs": [],
260 | "source": [
261 | "# compare to m\n",
262 | "m"
263 | ]
264 | },
265 | {
266 | "cell_type": "markdown",
267 | "metadata": {
268 | "slideshow": {
269 | "slide_type": "slide"
270 | }
271 | },
272 | "source": [
273 | "## Vigenère Cipher\n",
274 | "The Vigenère cipher is a method of encrypting alphabetic text by using a series of different Caesar ciphers based on the letters of a keyword.\n",
275 | "\n",
276 | "Let $m=m_0 \\| m_1 \\| \\dots \\| m_n$ be the plaintext, $c=c_0 \\| c_1 \\| \\dots \\| c_n$ be the ciphertext and $k=k_0 \\| k_1 \\| \\dots \\| k_m$ be the encryption key (which is repeated until it matches the length of the plaintext).\n",
277 | "\n",
278 | "Encryption works as follows:\n",
279 | "$c_i = Enc(m_i) = m_i + k_i \\mod 26$\n",
280 | "\n",
281 | "Decryption can be performed as:\n",
282 | "$m_i = Dec(c_i) = m_i - k_i \\mod 26$"
283 | ]
284 | },
285 | {
286 | "cell_type": "code",
287 | "execution_count": null,
288 | "metadata": {
289 | "slideshow": {
290 | "slide_type": "slide"
291 | }
292 | },
293 | "outputs": [],
294 | "source": [
295 | "# We use a Vigenère cipher with a key of 14 letters\n",
296 | "\n",
297 | "k = AZ('ABCDEFGHIJKLMN')\n",
298 | "\n",
299 | "m = AZ(\"THECATINTHEHAT\")\n",
300 | "m"
301 | ]
302 | },
303 | {
304 | "cell_type": "code",
305 | "execution_count": null,
306 | "metadata": {
307 | "slideshow": {
308 | "slide_type": "-"
309 | }
310 | },
311 | "outputs": [],
312 | "source": [
313 | "c = encipher_vigenere(m,k)\n",
314 | "c"
315 | ]
316 | },
317 | {
318 | "cell_type": "code",
319 | "execution_count": null,
320 | "metadata": {
321 | "slideshow": {
322 | "slide_type": "-"
323 | }
324 | },
325 | "outputs": [],
326 | "source": [
327 | "decipher_vigenere(c,k)"
328 | ]
329 | },
330 | {
331 | "cell_type": "markdown",
332 | "metadata": {
333 | "slideshow": {
334 | "slide_type": "slide"
335 | }
336 | },
337 | "source": [
338 | "A Vigenère cipher can be attacked with frequency analysis if we know the size of the key.\n",
339 | "\n",
340 | "If the key-length is $t$, then the ciphertext characters $c_1$, $c_{1+t}$, $c_{1+2t}$, $\\dots$ are encrypted using the same shift. Therefore, the frequencies of such characters are expected to be identical to the frequencies of standard English text."
341 | ]
342 | },
343 | {
344 | "cell_type": "markdown",
345 | "metadata": {
346 | "slideshow": {
347 | "slide_type": "slide"
348 | }
349 | },
350 | "source": [
351 | "To find the key size we use the Index of Coincidence Method.\n",
352 | "\n",
353 | "We sample the ciphertext with period $t$ and calculate the frequencies.\n",
354 | "\n",
355 | "If the key length is $t$, then the letters in the sampled text have the same frequencies as in the plaintext language, otherwise the letters will occurr with roughly equal probability."
356 | ]
357 | },
358 | {
359 | "cell_type": "code",
360 | "execution_count": null,
361 | "metadata": {
362 | "slideshow": {
363 | "slide_type": "slide"
364 | }
365 | },
366 | "outputs": [],
367 | "source": [
368 | "ct = AZ(\"\"\"\n",
369 | "YOVTZFJBUOYIPWRLHISZQHEHCJMFJHMLDGGYDZDRDLKECXAYGAJSPFOWYRLWALNZWHOZSAFIFMH\n",
370 | "YVGWBNUVAHMLIWLULTLBTYJGZNJZLPJSZWTRHUABILVVKTBCVWGLKGSCWVUHNAZFOHHJWKMLIWA\n",
371 | "DCVJMXLEKSXYVBSHAKZSNYFOBJCZVSSJVQSYTRVORPEGHFUUNSWFJMFJSPVCNUFLRWLREPZAKGA\n",
372 | "TYIGKNKZWOSKKGRFFZOCZSUMBGBILVJUDQGTBCEMNTDWRNHKWDZYGGGJPJLCUSRUSGLWGFJAYWK\n",
373 | "TYCVDQHZFZDZLUQNUTLZDHEVKNAYGIYJFEAJUKSGJYZWGTMDWFJOFMGJOFDRJCVFHXPELVJPIUC\n",
374 | "SZVIIJUTWGYOVKSJCVFHXORNSYLIJWKPVVVFCVLCWALJSIORNSILJLFTFVVAJFVLWBPCDBTARLH\n",
375 | "JTGLHTLOHCZUULVJTKGAJAYWMMHMWDWLJWBYLUDWYACWPZAYGFWVILCRHEQHMLPOWQSJWSRSVKG\n",
376 | "YLIJWGSVLVFUSSFTXLWGMLIWOKAVJDJYYSDXZFESNUKWZQLTLAFFSWTTBEVKMPTZKNSCJSIBTWA\n",
377 | "DWYSBYHJEHTAYWQTTDGBUSRUSXVDWWSAVDZJJKECWLTSZRTFJSQVXAQFSRFRKHIDSXZVPQNARTZ\n",
378 | "JAYSBRFFOBBOZUVBPCDDJYTWWALZFHMLTAFHBDKHFUTWGNKVLONSNAHMHNWBTAYABLTFJSYORFO\n",
379 | "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ODLUSBIJCGHYLUOWYOXGFJZKGCILIWQYIVXCWLKZSJFVKCKAYWGULTLOYVIKIUVEAH\n",
595 | "XOVSRBPKZFJKVPHJUUWRRVLLVFUUKCQPKSFDLPWCKMZJSXHKLVJOZVSTBJTSFZKOVTZVUFFMKZO\n",
596 | "IZVVIHLUESNUKGAZYUWFFUUOVTZVABKVIEWSNMGWHLYSRHVEKWLUVVAJAFLVJORFURHEAVFKNSZ\n",
597 | "QLULVJTFFGYLIMDBPKZWSAYWHTTS\n",
598 | "\"\"\")"
599 | ]
600 | },
601 | {
602 | "cell_type": "code",
603 | "execution_count": null,
604 | "metadata": {
605 | "slideshow": {
606 | "slide_type": "slide"
607 | }
608 | },
609 | "outputs": [],
610 | "source": [
611 | "# Let's try a key length equal to 1\n",
612 | "t = 1\n",
613 | "\n",
614 | "# sample with step t\n",
615 | "p = ct[0::1]\n",
616 | "\n",
617 | "plot_frequencies(p)"
618 | ]
619 | },
620 | {
621 | "cell_type": "markdown",
622 | "metadata": {},
623 | "source": [
624 | "That the entropy of the uniform distribution is\n",
625 | "$$\n",
626 | " -\\sum_{i=0}^{25} \\frac{1}{26} \\log_2\\frac{1}{26} = \\log_2(26) = 4.7 \n",
627 | "$$\n",
628 | "\n",
629 | "The histogram with $t = 1$ is close to uniform."
630 | ]
631 | },
632 | {
633 | "cell_type": "code",
634 | "execution_count": null,
635 | "metadata": {},
636 | "outputs": [],
637 | "source": [
638 | "# We can test multiple key sizes\n",
639 | "e = []\n",
640 | "for t in range(1,10):\n",
641 | " p = ct[0::t]\n",
642 | " freq = collections.Counter(p)\n",
643 | " e.append(entropy(freq.values()))\n",
644 | "plt.bar(range(1,10),e)\n",
645 | "plt.show()"
646 | ]
647 | },
648 | {
649 | "cell_type": "code",
650 | "execution_count": null,
651 | "metadata": {
652 | "slideshow": {
653 | "slide_type": "slide"
654 | }
655 | },
656 | "outputs": [],
657 | "source": [
658 | "# Probably the key size is 5\n",
659 | "t = 5\n",
660 | "\n",
661 | "p = ct[0::t]\n",
662 | "\n",
663 | "plot_frequencies(p)"
664 | ]
665 | },
666 | {
667 | "cell_type": "code",
668 | "execution_count": null,
669 | "metadata": {
670 | "slideshow": {
671 | "slide_type": "slide"
672 | }
673 | },
674 | "outputs": [],
675 | "source": [
676 | "# The most common letter in the ciphertext (J) could be the letter E in the plaintext\n",
677 | "# The key would be\n",
678 | "ord(\"J\")-ord(\"E\")"
679 | ]
680 | },
681 | {
682 | "cell_type": "code",
683 | "execution_count": null,
684 | "metadata": {
685 | "slideshow": {
686 | "slide_type": "slide"
687 | }
688 | },
689 | "outputs": [],
690 | "source": [
691 | "# repeating for all the letters we find the key \"FHRSO\"\n",
692 | "decipher_vigenere(ct,\"FHRSO\")"
693 | ]
694 | },
695 | {
696 | "cell_type": "code",
697 | "execution_count": null,
698 | "metadata": {
699 | "slideshow": {
700 | "slide_type": "slide"
701 | }
702 | },
703 | "outputs": [],
704 | "source": [
705 | "# compare to the original plaintext\n",
706 | "m = \"\"\"\n",
707 | "THE BLACK CAT\n",
708 | "\n",
709 | " by Edgar Allan Poe\n",
710 | " (1843)\n",
711 | "\n",
712 | " FOR the most wild, yet most homely narrative which I am about to pen, I\n",
713 | "neither expect nor solicit belief. Mad indeed would I be to expect it, in a\n",
714 | "case where my very senses reject their own evidence. Yet, mad am I not --and\n",
715 | "very surely do I not dream. But to-morrow I die, and to-day I would\n",
716 | "unburthen my soul. My immediate purpose is to place before the world,\n",
717 | "plainly, succinctly, and without comment, a series of mere household events.\n",
718 | "In their consequences, these events have terrified --have tortured --have\n",
719 | "destroyed me. Yet I will not attempt to expound them. To me, they have\n",
720 | "presented little but Horror --to many they will seem less terrible than\n",
721 | "baroques. Hereafter, perhaps, some intellect may be found which will reduce\n",
722 | "my phantasm to the common-place --some intellect more calm, more logical,\n",
723 | "and far less excitable than my own, which will perceive, in the\n",
724 | "circumstances I detail with awe, nothing more than an ordinary succession of\n",
725 | "very natural causes and effects.\n",
726 | " From my infancy I was noted for the docility and humanity of my\n",
727 | "disposition. My tenderness of heart was even so conspicuous as to make me\n",
728 | "the jest of my companions. I was especially fond of animals, and was\n",
729 | "indulged by my parents with a great variety of pets. With these I spent most\n",
730 | "of my time, and never was so happy as when feeding and caressing them. This\n",
731 | "peculiar of character grew with my growth, and in my manhood, I derived from\n",
732 | "it one of my principal sources of pleasure. To those who have cherished an\n",
733 | "affection for a faithful and sagacious dog, I need hardly be at the trouble\n",
734 | "of explaining the nature or the intensity of the gratification thus\n",
735 | "derivable. There is something in the unselfish and self-sacrificing love of\n",
736 | "a brute, which goes directly to the heart of him who has had frequent\n",
737 | "occasion to test the paltry friendship and gossamer fidelity of mere Man.\n",
738 | " I married early, and was happy to find in my wife a disposition not\n",
739 | "uncongenial with my own. Observing my partiality for domestic pets, she lost\n",
740 | "no opportunity of procuring those of the most agreeable kind. We had birds,\n",
741 | "gold fish, a fine dog, rabbits, a small monkey, and a cat.\n",
742 | " This latter was a remarkably large and beautiful animal, entirely black,\n",
743 | "and sagacious to an astonishing degree. In speaking of his intelligence, my\n",
744 | "wife, who at heart was not a little tinctured with superstition, made\n",
745 | "frequent allusion to the ancient popular notion, which regarded all black\n",
746 | "cats as witches in disguise. Not that she was ever serious upon this point\n",
747 | "--and I mention the matter at all for no better reason than that it happens,\n",
748 | "just now, to be remembered.\n",
749 | " Pluto --this was the cat's name --was my favorite pet and playmate. I\n",
750 | "alone fed him, and he attended me wherever I went about the house. It was\n",
751 | "even with difficulty that I could prevent him from following me through the\n",
752 | "streets.\n",
753 | " Our friendship lasted, in this manner, for several years, during which my\n",
754 | "general temperament and character --through the instrumentality of the Fiend\n",
755 | "Intemperance --had (I blush to confess it) experienced a radical alteration\n",
756 | "for the worse. I grew, day by day, more moody, more irritable, more\n",
757 | "regardless of the feelings of others. I suffered myself to use intemperate\n",
758 | "language to my At length, I even offered her personal violence. My pets, of\n",
759 | "course, were made to feel the change in my disposition. I not only\n",
760 | "neglected, but ill-used them. For Pluto, however, I still retained\n",
761 | "sufficient regard to restrain me from maltreating him, as I made no scruple\n",
762 | "of maltreating the rabbits, the monkey, or even the dog, when by accident,\n",
763 | "or through affection, they came in my way. But my disease grew upon me --for\n",
764 | "what disease is like Alcohol! --and at length even Pluto, who was now\n",
765 | "becoming old, and consequently somewhat peevish --even Pluto began to\n",
766 | "experience the effects of my ill temper.\n",
767 | " One night, returning home, much intoxicated, from one of my haunts about\n",
768 | "town, I fancied that the cat avoided my presence. I seized him; when, in his\n",
769 | "fright at my violence, he inflicted a slight wound upon my hand with his\n",
770 | "teeth. The fury of a demon instantly possessed me. I knew myself no longer.\n",
771 | "My original soul seemed, at once, to take its flight from my body; and a\n",
772 | "more than fiendish malevolence, gin-nurtured, thrilled every fibre of my\n",
773 | "frame. I took from my waistcoat-pocket a pen-knife, opened it, grasped the\n",
774 | "poor beast by the throat, and deliberately cut one of its eyes from the\n",
775 | "socket! I blush, I burn, I shudder, while I pen the damnable atrocity.\n",
776 | " When reason returned with the morning --when I had slept off the fumes of\n",
777 | "the night's debauch --I experienced a sentiment half of horror, half of\n",
778 | "remorse, for the crime of which I had been guilty; but it was, at best, a\n",
779 | "feeble and equivocal feeling, and the soul remained untouched. I again\n",
780 | "plunged into excess, and soon drowned in wine all memory of the deed.\n",
781 | " In the meantime the cat slowly recovered. The socket of the lost eye\n",
782 | "presented, it is true, a frightful appearance, but he no longer appeared to\n",
783 | "suffer any pain. He went about the house as usual, but, as might be\n",
784 | "expected, fled in extreme terror at my approach. I had so much of my old\n",
785 | "heart left, as to be at first grieved by this evident dislike on the part of\n",
786 | "a creature which had once so loved me. But this feeling soon gave place to\n",
787 | "irritation. And then came, as if to my final and irrevocable overthrow, the\n",
788 | "spirit of PERVERSENESS. Of this spirit philosophy takes no account. Yet I am\n",
789 | "not more sure that my soul lives, than I am that perverseness is one of the\n",
790 | "primitive impulses of the human heart --one of the indivisible primary\n",
791 | "faculties, or sentiments, which give direction to the character of Man. Who\n",
792 | "has not, a hundred times, found himself committing a vile or a silly action,\n",
793 | "for no other reason than because he knows he should not? Have we not a\n",
794 | "perpetual inclination, in the teeth of our best judgment, to violate that\n",
795 | "which is Law, merely because we understand it to be such? This spirit of\n",
796 | "perverseness, I say, came to my final overthrow. It was this unfathomable\n",
797 | "longing of the soul to vex itself --to offer violence to its own nature --to\n",
798 | "do wrong for the wrong's sake only --that urged me to continue and finally\n",
799 | "to consummate the injury I had inflicted upon the unoffending brute. One\n",
800 | "morning, in cool blood, I slipped a noose about its neck and hung it to the\n",
801 | "limb of a tree; --hung it with the tears streaming from my eyes, and with\n",
802 | "the bitterest remorse at my heart; --hung it because I knew that it had\n",
803 | "loved me, and because I felt it had given me no reason of offence; --hung it\n",
804 | "because I knew that in so doing I was committing a sin --a deadly sin that\n",
805 | "would so jeopardize my immortal soul as to place it --if such a thing were\n",
806 | "possible --even beyond the reach of the infinite mercy of the Most Merciful\n",
807 | "and Most Terrible God.\n",
808 | " On the night of the day on which this cruel deed was done, I was aroused\n",
809 | "from sleep by the cry of fire. The curtains of my bed were in flames. The\n",
810 | "whole house was blazing. It was with great difficulty that my wife, a\n",
811 | "servant, and myself, made our escape from the conflagration. The destruction\n",
812 | "was complete. My entire worldly wealth was swallowed up, and I resigned\n",
813 | "myself thenceforward to despair.\n",
814 | " I am above the weakness of seeking to establish a sequence of cause and\n",
815 | "effect, between the disaster and the atrocity. But I am detailing a chain of\n",
816 | "facts --and wish not to leave even a possible link imperfect. On the day\n",
817 | "succeeding the fire, I visited the ruins. The walls, with one exception, had\n",
818 | "fallen in. This exception was found in a compartment wall, not very thick,\n",
819 | "which stood about the middle of the house, and against which had rested the\n",
820 | "head of my bed. The plastering had here, in great measure, resisted the\n",
821 | "action of the fire --a fact which I attributed to its having been recently\n",
822 | "spread. About this wall a dense crowd were collected, and many persons\n",
823 | "seemed to be examining a particular portion of it with every minute and\n",
824 | "eager attention. The words \"strange!\" \"singular!\" and other similar\n",
825 | "expressions, excited my curiosity. I approached and saw, as if graven in bas\n",
826 | "relief upon the white surface, the figure of a gigantic cat. The impression\n",
827 | "was given with an accuracy truly marvellous. There was a rope about the\n",
828 | "animal's neck.\n",
829 | " When I first beheld this apparition --for I could scarcely regard it as\n",
830 | "less --my wonder and my terror were extreme. But at length reflection came\n",
831 | "to my aid. The cat, I remembered, had been hung in a garden adjacent to the\n",
832 | "house. Upon the alarm of fire, this garden had been immediately filled by\n",
833 | "the crowd --by some one of whom the animal must have been cut from the tree\n",
834 | "and thrown, through an open window, into my chamber. This had probably been\n",
835 | "done with the view of arousing me from sleep. The falling of other walls had\n",
836 | "compressed the victim of my cruelty into the substance of the freshly-spread\n",
837 | "plaster; the lime of which, had then with the flames, and the ammonia from\n",
838 | "the carcass, accomplished the portraiture as I saw it.\n",
839 | " Although I thus readily accounted to my reason, if not altogether to my\n",
840 | "conscience, for the startling fact 'just detailed, it did not the less fall\n",
841 | "to make a deep impression upon my fancy. For months I could not rid myself\n",
842 | "of the phantasm of the cat; and, during this period, there came back into my\n",
843 | "spirit a half-sentiment that seemed, but was not, remorse. I went so far as\n",
844 | "to regret the loss of the animal, and to look about me, among the vile\n",
845 | "haunts which I now habitually frequented, for another pet of the same\n",
846 | "species, and of somewhat similar appearance, with which to supply its place.\n",
847 | "\n",
848 | " One night as I sat, half stupefied, in a den of more than infamy, my\n",
849 | "attention was suddenly drawn to some black object, reposing upon the head of\n",
850 | "one of the immense hogsheads of Gin, or of Rum, which constituted the chief\n",
851 | "furniture of the apartment. I had been looking steadily at the top of this\n",
852 | "hogshead for some minutes, and what now caused me surprise was the fact that\n",
853 | "I had not sooner perceived the object thereupon. I approached it, and\n",
854 | "touched it with my hand. It was a black cat --a very large one --fully as\n",
855 | "large as Pluto, and closely resembling him in every respect but one. Pluto\n",
856 | "had not a white hair upon any portion of his body; but this cat had a large,\n",
857 | "although indefinite splotch of white, covering nearly the whole region of\n",
858 | "the breast.\n",
859 | " Upon my touching him, he immediately arose, purred loudly, rubbed against\n",
860 | "my hand, and appeared delighted with my notice. This, then, was the very\n",
861 | "creature of which I was in search. I at once offered to purchase it of the\n",
862 | "landlord; but this person made no claim to it --knew nothing of it --had\n",
863 | "never seen it before.\n",
864 | " I continued my caresses, and, when I prepared to go home, the animal\n",
865 | "evinced a disposition to accompany me. I permitted it to do so; occasionally\n",
866 | "stooping and patting it as I proceeded. When it reached the house it\n",
867 | "domesticated itself at once, and became immediately a great favorite with my\n",
868 | "wife.\n",
869 | " For my own part, I soon found a dislike to it arising within me. This was\n",
870 | "just the reverse of what I had anticipated; but I know not how or why it was\n",
871 | "--its evident fondness for myself rather disgusted and annoyed. By slow\n",
872 | "degrees, these feelings of disgust and annoyance rose into the bitterness of\n",
873 | "hatred. I avoided the creature; a certain sense of shame, and the\n",
874 | "remembrance of my former deed of cruelty, preventing me from physically\n",
875 | "abusing it. I did not, for some weeks, strike, or otherwise violently ill\n",
876 | "use it; but gradually --very gradually --I came to look upon it with\n",
877 | "unutterable loathing, and to flee silently from its odious presence, as from\n",
878 | "the breath of a pestilence.\n",
879 | " What added, no doubt, to my hatred of the beast, was the discovery, on\n",
880 | "the morning after I brought it home, that, like Pluto, it also had been\n",
881 | "deprived of one of its eyes. This circumstance, however, only endeared it to\n",
882 | "my wife, who, as I have already said, possessed, in a high degree, that\n",
883 | "humanity of feeling which had once been my distinguishing trait, and the\n",
884 | "source of many of my simplest and purest pleasures.\n",
885 | " With my aversion to this cat, however, its partiality for myself seemed\n",
886 | "to increase. It followed my footsteps with a pertinacity which it would be\n",
887 | "difficult to make the reader comprehend. Whenever I sat, it would crouch\n",
888 | "beneath my chair, or spring upon my knees, covering me with its loathsome\n",
889 | "caresses. If I arose to walk it would get between my feet and thus nearly\n",
890 | "throw me down, or, fastening its long and sharp claws in my dress, clamber,\n",
891 | "in this manner, to my breast. At such times, although I longed to destroy it\n",
892 | "with a blow, I was yet withheld from so doing, partly it at by a memory of\n",
893 | "my former crime, but chiefly --let me confess it at once --by absolute dread\n",
894 | "of the beast.\n",
895 | " This dread was not exactly a dread of physical evil-and yet I should be\n",
896 | "at a loss how otherwise to define it. I am almost ashamed to own --yes, even\n",
897 | "in this felon's cell, I am almost ashamed to own --that the terror and\n",
898 | "horror with which the animal inspired me, had been heightened by one of the\n",
899 | "merest chimaeras it would be possible to conceive. My wife had called my\n",
900 | "attention, more than once, to the character of the mark of white hair, of\n",
901 | "which I have spoken, and which constituted the sole visible difference\n",
902 | "between the strange beast and the one I had y si destroyed. The reader will\n",
903 | "remember that this mark, although large, had been originally very\n",
904 | "indefinite; but, by slow degrees --degrees nearly imperceptible, and which\n",
905 | "for a long time my Reason struggled to reject as fanciful --it had, at\n",
906 | "length, assumed a rigorous distinctness of outline. It was now the\n",
907 | "representation of an object that I shudder to name --and for this, above\n",
908 | "all, I loathed, and dreaded, and would have rid myself of the monster had I\n",
909 | "dared --it was now, I say, the image of a hideous --of a ghastly thing --of\n",
910 | "the GALLOWS! --oh, mournful and terrible engine of Horror and of Crime --of\n",
911 | "Agony and of Death!\n",
912 | " And now was I indeed wretched beyond the wretchedness of mere Humanity.\n",
913 | "And a brute beast --whose fellow I had contemptuously destroyed --a brute\n",
914 | "beast to work out for me --for me a man, fashioned in the image of the High\n",
915 | "God --so much of insufferable wo! Alas! neither by day nor by night knew I\n",
916 | "the blessing of Rest any more! During the former the creature left me no\n",
917 | "moment alone; and, in the latter, I started, hourly, from dreams of\n",
918 | "unutterable fear, to find the hot breath of the thing upon my face, and its\n",
919 | "vast weight --an incarnate Night-Mare that I had no power to shake off\n",
920 | "--incumbent eternally upon my heart!\n",
921 | " Beneath the pressure of torments such as these, the feeble remnant of the\n",
922 | "good within me succumbed. Evil thoughts became my sole intimates --the\n",
923 | "darkest and most evil of thoughts. The moodiness of my usual temper\n",
924 | "increased to hatred of all things and of all mankind; while, from the\n",
925 | "sudden, frequent, and ungovernable outbursts of a fury to which I now\n",
926 | "blindly abandoned myself, my uncomplaining wife, alas! was the most usual\n",
927 | "and the most patient of sufferers.\n",
928 | " One day she accompanied me, upon some household errand, into the cellar\n",
929 | "of the old building which our poverty compelled us to inhabit. The cat\n",
930 | "followed me down the steep stairs, and, nearly throwing me headlong,\n",
931 | "exasperated me to madness. Uplifting an axe, and forgetting, in my wrath,\n",
932 | "the childish dread which had hitherto stayed my hand, I aimed a blow at the\n",
933 | "animal which, of course, would have proved instantly fatal had it descended\n",
934 | "as I wished. But this blow was arrested by the hand of my wife. Goaded, by\n",
935 | "the interference, into a rage more than demoniacal, I withdrew my arm from\n",
936 | "her grasp and buried the axe in her brain. She fell dead upon the spot,\n",
937 | "without a groan.\n",
938 | " This hideous murder accomplished, I set myself forthwith, and with entire\n",
939 | "deliberation, to the task of concealing the body. I knew that I could not\n",
940 | "remove it from the house, either by day or by night, without the risk of\n",
941 | "being observed by the neighbors. Many projects entered my mind. At one\n",
942 | "period I thought of cutting the corpse into minute fragments, and destroying\n",
943 | "them by fire. At another, I resolved to dig a grave for it in the floor of\n",
944 | "the cellar. Again, I deliberated about casting it in the well in the yard\n",
945 | "--about packing it in a box, as if merchandize, with the usual arrangements,\n",
946 | "and so getting a porter to take it from the house. Finally I hit upon what I\n",
947 | "considered a far better expedient than either of these. I determined to wall\n",
948 | "it up in the cellar --as the monks of the middle ages are recorded to have\n",
949 | "walled up their victims.\n",
950 | " For a purpose such as this the cellar was well adapted. Its walls were\n",
951 | "loosely constructed, and had lately been plastered throughout with a rough\n",
952 | "plaster, which the dampness of the atmosphere had prevented from hardening.\n",
953 | "Moreover, in one of the walls was a projection, caused by a false chimney,\n",
954 | "or fireplace, that had been filled up, and made to resemble the rest of the\n",
955 | "cellar. I made no doubt that I could readily displace the at this point,\n",
956 | "insert the corpse, and wall the whole up as before, so that no eye could\n",
957 | "detect anything suspicious.\n",
958 | " And in this calculation I was not deceived. By means of a crow-bar I\n",
959 | "easily dislodged the bricks, and, having carefully deposited the body\n",
960 | "against the inner wall, I propped it in that position, while, with little\n",
961 | "trouble, I re-laid the whole structure as it originally stood. Having\n",
962 | "procured mortar, sand, and hair, with every possible precaution, I prepared\n",
963 | "a plaster could not every poss be distinguished from the old, and with this\n",
964 | "I very carefully went over the new brick-work. When I had finished, I felt\n",
965 | "satisfied that all was right. The wall did not present the slightest\n",
966 | "appearance of having been disturbed. The rubbish on the floor was picked up\n",
967 | "with the minutest care. I looked around triumphantly, and said to myself\n",
968 | "--\"Here at least, then, my labor has not been in vain.\"\n",
969 | " My next step was to look for the beast which had been the cause of so\n",
970 | "much wretchedness; for I had, at length, firmly resolved to put it to death.\n",
971 | "Had I been able to meet with it, at the moment, there could have been no\n",
972 | "doubt of its fate; but it appeared that the crafty animal had been alarmed\n",
973 | "at the violence of my previous anger, and forebore to present itself in my\n",
974 | "present mood. It is impossible to describe, or to imagine, the deep, the\n",
975 | "blissful sense of relief which the absence of the detested creature\n",
976 | "occasioned in my bosom. It did not make its appearance during the night\n",
977 | "--and thus for one night at least, since its introduction into the house, I\n",
978 | "soundly and tranquilly slept; aye, slept even with the burden of murder upon\n",
979 | "my soul!\n",
980 | " The second and the third day passed, and still my tormentor came not.\n",
981 | "Once again I breathed as a free-man. The monster, in terror, had fled the\n",
982 | "premises forever! I should behold it no more! My happiness was supreme! The\n",
983 | "guilt of my dark deed disturbed me but little. Some few inquiries had been\n",
984 | "made, but these had been readily answered. Even a search had been instituted\n",
985 | "--but of course nothing was to be discovered. I looked upon my future\n",
986 | "felicity as secured.\n",
987 | " Upon the fourth day of the assassination, a party of the police came,\n",
988 | "very unexpectedly, into the house, and proceeded again to make rigorous\n",
989 | "investigation of the premises. Secure, however, in the inscrutability of my\n",
990 | "place of concealment, I felt no embarrassment whatever. The officers bade me\n",
991 | "accompany them in their search. They left no nook or corner unexplored. At\n",
992 | "length, for the third or fourth time, they descended into the cellar. I\n",
993 | "quivered not in a muscle. My heart beat calmly as that of one who slumbers\n",
994 | "in innocence. I walked the cellar from end to end. I folded my arms upon my\n",
995 | "bosom, and roamed easily to and fro. The police were thoroughly satisfied\n",
996 | "and prepared to depart. The glee at my heart was too strong to be\n",
997 | "restrained. I burned to say if but one word, by way of triumph, and to\n",
998 | "render doubly sure their assurance of my guiltlessness.\n",
999 | " \"Gentlemen,\" I said at last, as the party ascended the steps, \"I delight\n",
1000 | "to have allayed your suspicions. I wish you all health, and a little more\n",
1001 | "courtesy. By the bye, gentlemen, this --this is a very well constructed\n",
1002 | "house.\" (In the rabid desire to say something easily, I scarcely knew what I\n",
1003 | "uttered at all.) --\"I may say an excellently well constructed house. These\n",
1004 | "walls --are you going, gentlemen? --these walls are solidly put together\";\n",
1005 | "and here, through the mere phrenzy of bravado, I rapped heavily, with a cane\n",
1006 | "which I held in my hand, upon that very portion of the brick-work behind\n",
1007 | "which stood the corpse of the wife of my bosom.\n",
1008 | " But may God shield and deliver me from the fangs of the Arch-Fiend! No\n",
1009 | "sooner had the reverberation of my blows sunk into silence than I was\n",
1010 | "answered by a voice from within the tomb! --by a cry, at first muffled and\n",
1011 | "broken, like the sobbing of a child, and then quickly swelling into one\n",
1012 | "long, loud, and continuous scream, utterly anomalous and inhuman --a howl\n",
1013 | "--a wailing shriek, half of horror and half of triumph, such as might have\n",
1014 | "arisen only out of hell, conjointly from the throats of the damned in their\n",
1015 | "agony and of the demons that exult in the damnation.\n",
1016 | " Of my own thoughts it is folly to speak. Swooning, I staggered to the\n",
1017 | "opposite wall. For one instant the party upon the stairs remained\n",
1018 | "motionless, through extremity of terror and of awe. In the next, a dozen\n",
1019 | "stout arms were tolling at the wall. It fell bodily. The corpse, already\n",
1020 | "greatly decayed and clotted with gore, stood erect before the eyes of the\n",
1021 | "spectators. Upon its head, with red extended mouth and solitary eye of fire,\n",
1022 | "sat the hideous beast whose craft had seduced me into murder, and whose\n",
1023 | "informing voice had consigned me to the hangman. I had walled the monster up\n",
1024 | "within the tomb!\n",
1025 | "\"\"\""
1026 | ]
1027 | },
1028 | {
1029 | "cell_type": "code",
1030 | "execution_count": null,
1031 | "metadata": {},
1032 | "outputs": [],
1033 | "source": []
1034 | }
1035 | ],
1036 | "metadata": {
1037 | "kernelspec": {
1038 | "display_name": "Python 3 (ipykernel)",
1039 | "language": "python",
1040 | "name": "python3"
1041 | },
1042 | "language_info": {
1043 | "codemirror_mode": {
1044 | "name": "ipython",
1045 | "version": 3
1046 | },
1047 | "file_extension": ".py",
1048 | "mimetype": "text/x-python",
1049 | "name": "python",
1050 | "nbconvert_exporter": "python",
1051 | "pygments_lexer": "ipython3",
1052 | "version": "3.9.7"
1053 | }
1054 | },
1055 | "nbformat": 4,
1056 | "nbformat_minor": 2
1057 | }
1058 |
--------------------------------------------------------------------------------
/DHKE.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Diffie-Hellman Key Exchange"
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "from cryptography.hazmat.primitives import hashes\n",
17 | "from cryptography.hazmat.primitives.asymmetric import dh\n",
18 | "from cryptography.hazmat.primitives.kdf.hkdf import HKDF\n",
19 | "from cryptography.hazmat.primitives.serialization import (\n",
20 | " Encoding, ParameterFormat, PublicFormat,\n",
21 | " load_pem_parameters, load_pem_public_key\n",
22 | ")"
23 | ]
24 | },
25 | {
26 | "cell_type": "markdown",
27 | "metadata": {},
28 | "source": [
29 | "We play the role of Alice and generate the parameters ($p$, $g$, $q$)"
30 | ]
31 | },
32 | {
33 | "cell_type": "code",
34 | "execution_count": null,
35 | "metadata": {},
36 | "outputs": [],
37 | "source": [
38 | "parameters = dh.generate_parameters(generator=2, key_size=1024)"
39 | ]
40 | },
41 | {
42 | "cell_type": "markdown",
43 | "metadata": {},
44 | "source": [
45 | "We need to send the parameters to Bob, so we serialize the parameters into a string that can be sent over the Internet.\n",
46 | "Bob will load the parameters with the command `parameters = load_pem_parameters(b'...string...')`"
47 | ]
48 | },
49 | {
50 | "cell_type": "code",
51 | "execution_count": null,
52 | "metadata": {},
53 | "outputs": [],
54 | "source": [
55 | "# If you are Bob, comment the following line\n",
56 | "parameters.parameter_bytes(Encoding.PEM,ParameterFormat.PKCS3)\n",
57 | "\n",
58 | "# If you are Bob, uncomment the following line and write the DH parameter string that you received from Alice\n",
59 | "# parameters = load_pem_parameters(b'...parameter string...')"
60 | ]
61 | },
62 | {
63 | "cell_type": "code",
64 | "execution_count": null,
65 | "metadata": {},
66 | "outputs": [],
67 | "source": [
68 | "# Now generate the local keypair\n",
69 | "local_private_key = parameters.generate_private_key()\n",
70 | "local_public_key = local_private_key.public_key()"
71 | ]
72 | },
73 | {
74 | "cell_type": "code",
75 | "execution_count": null,
76 | "metadata": {},
77 | "outputs": [],
78 | "source": [
79 | "# We need to send the local public key to the remote host\n",
80 | "# The remote host will load with the command\n",
81 | "# remote_public_key = load_pem_public_key(b'...string...')\n",
82 | "local_public_key.public_bytes(Encoding.PEM,PublicFormat.SubjectPublicKeyInfo)"
83 | ]
84 | },
85 | {
86 | "cell_type": "code",
87 | "execution_count": null,
88 | "metadata": {},
89 | "outputs": [],
90 | "source": [
91 | "# If you have the remote public key, uncomment the following line\n",
92 | "# remote_public_key = load_pem_public_key(\"...string...\")\n",
93 | "\n",
94 | "# If you do not have the remote public key and are just testing, you can generate a test key with the following lines\n",
95 | "# If you have the remote public key, comment the following lines\n",
96 | "test_private_key = parameters.generate_private_key()\n",
97 | "remote_public_key = test_private_key.public_key()"
98 | ]
99 | },
100 | {
101 | "cell_type": "code",
102 | "execution_count": null,
103 | "metadata": {},
104 | "outputs": [],
105 | "source": [
106 | "# This is the shared group element\n",
107 | "shared_secret = local_private_key.exchange(remote_public_key)"
108 | ]
109 | },
110 | {
111 | "cell_type": "code",
112 | "execution_count": null,
113 | "metadata": {},
114 | "outputs": [],
115 | "source": [
116 | "# You can use derived_key to encrypt a message using any symmetric cipher\n",
117 | "# If possible prefer an authenticated\n",
118 | "derived_key = HKDF(\n",
119 | " algorithm=hashes.SHA256(),\n",
120 | " length=32,\n",
121 | " salt=None,\n",
122 | " info=b'some shared data',\n",
123 | ").derive(shared_secret)\n",
124 | "derived_key"
125 | ]
126 | },
127 | {
128 | "cell_type": "markdown",
129 | "metadata": {},
130 | "source": [
131 | "## Laboratory"
132 | ]
133 | },
134 | {
135 | "cell_type": "markdown",
136 | "metadata": {},
137 | "source": [
138 | "Pick a classmate, decide who's Alice and who's Bob. Generate a key and send a message.\n",
139 | "You can use email or chat to exchange the protocol messages."
140 | ]
141 | }
142 | ],
143 | "metadata": {
144 | "kernelspec": {
145 | "display_name": "Python 3 (ipykernel)",
146 | "language": "python",
147 | "name": "python3"
148 | },
149 | "language_info": {
150 | "codemirror_mode": {
151 | "name": "ipython",
152 | "version": 3
153 | },
154 | "file_extension": ".py",
155 | "mimetype": "text/x-python",
156 | "name": "python",
157 | "nbconvert_exporter": "python",
158 | "pygments_lexer": "ipython3",
159 | "version": "3.9.12"
160 | }
161 | },
162 | "nbformat": 4,
163 | "nbformat_minor": 2
164 | }
165 |
--------------------------------------------------------------------------------
/DSA.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Legacy DSA\n",
8 | "(it is a legacy algorithm because it does not use Elliptic Curves)"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": 133,
14 | "metadata": {},
15 | "outputs": [],
16 | "source": [
17 | "from sympy.ntheory import isprime\n",
18 | "\n",
19 | "from cryptography.hazmat.primitives import hashes\n",
20 | "from cryptography.hazmat.primitives.asymmetric import dsa\n",
21 | "from cryptography.hazmat.primitives.asymmetric import utils #decode_dss_signature"
22 | ]
23 | },
24 | {
25 | "cell_type": "markdown",
26 | "metadata": {},
27 | "source": [
28 | "DSA works over a modular group $Z_p$, with $p$ prime.\n",
29 | "\n",
30 | "The private key is $x \\in [0,q)$.\n",
31 | "\n",
32 | "The public key is $y = g^x \\mod p$"
33 | ]
34 | },
35 | {
36 | "cell_type": "code",
37 | "execution_count": 154,
38 | "metadata": {},
39 | "outputs": [
40 | {
41 | "name": "stdout",
42 | "output_type": "stream",
43 | "text": [
44 | "Private key is: 961379271991097943513107905027321113521197974689\n",
45 | "Public key is : 48477392754393955024438228634301590594143208439654261402727738814431244365383291877571586040764824333019609272369268314232735617882729981394183302519262765414636339542136111572084592255503665718126044923788418771871782266374209405133883754338260355467090455976840997696455985413893208152786415108744976526421\n"
46 | ]
47 | }
48 | ],
49 | "source": [
50 | "private_key = dsa.generate_private_key( key_size=1024 )\n",
51 | "public_key = private_key.public_key()\n",
52 | "chosen_hash = hashes.SHA1()\n",
53 | "\n",
54 | "print(\"Private key is: %d\" % private_key.private_numbers().x)\n",
55 | "print(\"Public key is : %s\" % public_key.public_numbers().y)"
56 | ]
57 | },
58 | {
59 | "cell_type": "code",
60 | "execution_count": 155,
61 | "metadata": {},
62 | "outputs": [],
63 | "source": [
64 | "# parameters\n",
65 | "# The group is Zp\n",
66 | "p = private_key.private_numbers().public_numbers.parameter_numbers.p\n",
67 | "# The order is q\n",
68 | "q = private_key.private_numbers().public_numbers.parameter_numbers.q\n",
69 | "# The group generator is g\n",
70 | "g = private_key.private_numbers().public_numbers.parameter_numbers.g\n",
71 | "# The private key is x\n",
72 | "x = private_key.private_numbers().x\n",
73 | "# The public key is y\n",
74 | "y = private_key.private_numbers().public_numbers.y"
75 | ]
76 | },
77 | {
78 | "cell_type": "code",
79 | "execution_count": 156,
80 | "metadata": {},
81 | "outputs": [
82 | {
83 | "data": {
84 | "text/plain": [
85 | "True"
86 | ]
87 | },
88 | "execution_count": 156,
89 | "metadata": {},
90 | "output_type": "execute_result"
91 | }
92 | ],
93 | "source": [
94 | "# Is q prime?\n",
95 | "isprime(q)"
96 | ]
97 | },
98 | {
99 | "cell_type": "code",
100 | "execution_count": 157,
101 | "metadata": {},
102 | "outputs": [
103 | {
104 | "data": {
105 | "text/plain": [
106 | "0"
107 | ]
108 | },
109 | "execution_count": 157,
110 | "metadata": {},
111 | "output_type": "execute_result"
112 | }
113 | ],
114 | "source": [
115 | "# Does q divide p-1?\n",
116 | "(p-1) % q"
117 | ]
118 | },
119 | {
120 | "cell_type": "code",
121 | "execution_count": 158,
122 | "metadata": {},
123 | "outputs": [
124 | {
125 | "data": {
126 | "text/plain": [
127 | "True"
128 | ]
129 | },
130 | "execution_count": 158,
131 | "metadata": {},
132 | "output_type": "execute_result"
133 | }
134 | ],
135 | "source": [
136 | "# is y = g^x mod p?\n",
137 | "pow(g,x,p) == y"
138 | ]
139 | },
140 | {
141 | "cell_type": "markdown",
142 | "metadata": {},
143 | "source": [
144 | "## DSA signature\n",
145 | "To sign we need a random nonce $k \\in [1,q)$.\n",
146 | "\n",
147 | "The signature is the pair $(r,s)$ with\n",
148 | "$$ r = (g^k \\mod p) \\mod q $$\n",
149 | "$$ s = (k^{-1} (h(m) + xr) ) \\mod q$$"
150 | ]
151 | },
152 | {
153 | "cell_type": "code",
154 | "execution_count": 159,
155 | "metadata": {},
156 | "outputs": [
157 | {
158 | "data": {
159 | "text/plain": [
160 | "'302d021500a5f5b8c0a8947ffa138d628f07e180467ac4d77e021414f5e089dd521b0a171e07e6c412f52aadc6dc9b'"
161 | ]
162 | },
163 | "execution_count": 159,
164 | "metadata": {},
165 | "output_type": "execute_result"
166 | }
167 | ],
168 | "source": [
169 | "message = b'message'\n",
170 | "sig = private_key.sign(message,chosen_hash)\n",
171 | "\n",
172 | "# print the signature as hex\n",
173 | "sig.hex()"
174 | ]
175 | },
176 | {
177 | "cell_type": "code",
178 | "execution_count": 160,
179 | "metadata": {},
180 | "outputs": [
181 | {
182 | "data": {
183 | "text/plain": [
184 | "(947463253978480775779753407201527889614952781694,\n",
185 | " 119663058055035479453519114597518445521616166043)"
186 | ]
187 | },
188 | "execution_count": 160,
189 | "metadata": {},
190 | "output_type": "execute_result"
191 | }
192 | ],
193 | "source": [
194 | "(r,s)=utils.decode_dss_signature(sig)\n",
195 | "(r,s)"
196 | ]
197 | },
198 | {
199 | "cell_type": "markdown",
200 | "metadata": {},
201 | "source": [
202 | "## Can we verify the signature?\n",
203 | "\n",
204 | "We need\n",
205 | "$$ u_1 = h(m) s^{-1} \\mod q $$\n",
206 | "$$ u_2 = r s^{-1} \\mod q $$\n",
207 | "The signature is verified if\n",
208 | "$$ (g^{u_1}y^{u_2} \\mod p) \\mod q= r $$"
209 | ]
210 | },
211 | {
212 | "cell_type": "code",
213 | "execution_count": 161,
214 | "metadata": {},
215 | "outputs": [],
216 | "source": [
217 | "hasher = hashes.Hash(chosen_hash)\n",
218 | "hasher.update(message)\n",
219 | "digest = hasher.finalize()\n",
220 | "hm = int.from_bytes(digest,\"big\")"
221 | ]
222 | },
223 | {
224 | "cell_type": "code",
225 | "execution_count": 166,
226 | "metadata": {},
227 | "outputs": [
228 | {
229 | "data": {
230 | "text/plain": [
231 | "947463253978480775779753407201527889614952781694"
232 | ]
233 | },
234 | "execution_count": 166,
235 | "metadata": {},
236 | "output_type": "execute_result"
237 | }
238 | ],
239 | "source": [
240 | "u1 = (hm*pow(s,-1,q)) % q\n",
241 | "u2 = (r*pow(s,-1,q)) % q\n",
242 | "( (pow(g,u1,p)*pow(y,u2,p)) % p) % q"
243 | ]
244 | },
245 | {
246 | "cell_type": "code",
247 | "execution_count": 163,
248 | "metadata": {},
249 | "outputs": [
250 | {
251 | "data": {
252 | "text/plain": [
253 | "947463253978480775779753407201527889614952781694"
254 | ]
255 | },
256 | "execution_count": 163,
257 | "metadata": {},
258 | "output_type": "execute_result"
259 | }
260 | ],
261 | "source": [
262 | "r"
263 | ]
264 | },
265 | {
266 | "cell_type": "code",
267 | "execution_count": 168,
268 | "metadata": {},
269 | "outputs": [
270 | {
271 | "name": "stdout",
272 | "output_type": "stream",
273 | "text": [
274 | "OK\n"
275 | ]
276 | }
277 | ],
278 | "source": [
279 | "# Now we use the library function for signature verification\n",
280 | "try:\n",
281 | " public_key.verify(sig,message,chosen_hash)\n",
282 | " print(\"OK\")\n",
283 | "except:\n",
284 | " print(\"KO\")"
285 | ]
286 | },
287 | {
288 | "cell_type": "code",
289 | "execution_count": null,
290 | "metadata": {},
291 | "outputs": [],
292 | "source": []
293 | }
294 | ],
295 | "metadata": {
296 | "kernelspec": {
297 | "display_name": "Python 3 (ipykernel)",
298 | "language": "python",
299 | "name": "python3"
300 | },
301 | "language_info": {
302 | "codemirror_mode": {
303 | "name": "ipython",
304 | "version": 3
305 | },
306 | "file_extension": ".py",
307 | "mimetype": "text/x-python",
308 | "name": "python",
309 | "nbconvert_exporter": "python",
310 | "pygments_lexer": "ipython3",
311 | "version": "3.8.8"
312 | }
313 | },
314 | "nbformat": 4,
315 | "nbformat_minor": 2
316 | }
317 |
--------------------------------------------------------------------------------
/Elliptic Curves.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "## Elliptic Curves"
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": 12,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "from cryptography.hazmat.primitives import hashes\n",
17 | "from cryptography.hazmat.primitives.asymmetric import ec\n",
18 | "from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature\n",
19 | "from cryptography.hazmat.primitives.serialization import (\n",
20 | " Encoding, ParameterFormat, PublicFormat,\n",
21 | " load_pem_parameters, load_pem_public_key\n",
22 | ")"
23 | ]
24 | },
25 | {
26 | "cell_type": "markdown",
27 | "metadata": {},
28 | "source": [
29 | "## ECDSA\n",
30 | "\n",
31 | "ECDSA is a Digital Signature Algorithm. "
32 | ]
33 | },
34 | {
35 | "cell_type": "markdown",
36 | "metadata": {},
37 | "source": [
38 | "We use NIST curve SECP384r1. The key size is 384 bits.\n",
39 | "There is no need to generate parameters, because the standard already provides the curve equation, a generator and its order.\n",
40 | "\n",
41 | "We proceed with the generation of a private key and of the corresponding public key."
42 | ]
43 | },
44 | {
45 | "cell_type": "code",
46 | "execution_count": 3,
47 | "metadata": {},
48 | "outputs": [
49 | {
50 | "name": "stdout",
51 | "output_type": "stream",
52 | "text": [
53 | "Private key is: 33635704155717693405353620886293070477745946902130715807204371010321656843010542517516917047316355171352655336034740\n"
54 | ]
55 | }
56 | ],
57 | "source": [
58 | "private_key = ec.generate_private_key( ec.SECP384R1() )\n",
59 | "print(\"Private key is: %d\" % private_key.private_numbers().private_value)"
60 | ]
61 | },
62 | {
63 | "cell_type": "code",
64 | "execution_count": 4,
65 | "metadata": {},
66 | "outputs": [],
67 | "source": [
68 | "# Alternatively we can generate a key from an integer number (eg 1234) by using\n",
69 | "# private_key = ec.derive_private_key( 1234, ec.SECP384R1() )"
70 | ]
71 | },
72 | {
73 | "cell_type": "code",
74 | "execution_count": 5,
75 | "metadata": {},
76 | "outputs": [
77 | {
78 | "name": "stdout",
79 | "output_type": "stream",
80 | "text": [
81 | "Public key is : (x = 21263400085053286231367251025669544792039179980223644345493395480206074336308964713630426595512819598350299752861949, y = 5441330656277392332567791299355424278499640228179736378409126419609263799624126099855761639354640175647738023353457)\n"
82 | ]
83 | }
84 | ],
85 | "source": [
86 | "public_key = private_key.public_key()\n",
87 | "print(\"Public key is : (x = %s, y = %s)\" % (public_key.public_numbers().x,public_key.public_numbers().y))"
88 | ]
89 | },
90 | {
91 | "cell_type": "markdown",
92 | "metadata": {},
93 | "source": [
94 | "Remember that the private key is an integer, while the public key is a point. Now we can sign a message.\n",
95 | "The signature will be encoded using the DER rules, so it will be a string of bits."
96 | ]
97 | },
98 | {
99 | "cell_type": "code",
100 | "execution_count": 6,
101 | "metadata": {},
102 | "outputs": [
103 | {
104 | "name": "stdout",
105 | "output_type": "stream",
106 | "text": [
107 | "3065023100891e87c0d49e94d640d4425c6fcd8a8f38737589ca448b2ca0830002ed2bab341f427a7d96d752c62232c70783398f0a0230582f0ce0f0d05610bdeef2d8fdc10c8d523aa88cca3037f17a27fd524e03eda028a2ff9c6f28c40cd9570eceb6435e7c\n"
108 | ]
109 | }
110 | ],
111 | "source": [
112 | "data = b\"this is some data I'd like to sign\"\n",
113 | "signature = private_key.sign(\n",
114 | " data,\n",
115 | " ec.ECDSA(hashes.SHA256())\n",
116 | " )\n",
117 | "print(signature.hex())"
118 | ]
119 | },
120 | {
121 | "cell_type": "markdown",
122 | "metadata": {},
123 | "source": [
124 | "The DSA signature is randomized, so if we run the algorithm again we get a different signature. The interface does not ask for a nonce, so we cannot make the mistake of providing repeated nonces."
125 | ]
126 | },
127 | {
128 | "cell_type": "code",
129 | "execution_count": 7,
130 | "metadata": {},
131 | "outputs": [
132 | {
133 | "name": "stdout",
134 | "output_type": "stream",
135 | "text": [
136 | "30640230151ba8a8dd4ade8486df61b591e823f8420fa24a7d677c164ab41a05abdf68e35b15815448db4b33148976c40d5f3bc902307bbe53fbd31e258a098790ceb23d0bc92fe71b429bfdb6f1608bee652c7429a400fdc6e14cde80829747be7d7ad979b0\n"
137 | ]
138 | }
139 | ],
140 | "source": [
141 | "signature = private_key.sign(\n",
142 | " data,\n",
143 | " ec.ECDSA(hashes.SHA256())\n",
144 | " )\n",
145 | "print(signature.hex())"
146 | ]
147 | },
148 | {
149 | "cell_type": "markdown",
150 | "metadata": {},
151 | "source": [
152 | "We can decode the signature and retrieve the parameters $r$ and $s$"
153 | ]
154 | },
155 | {
156 | "cell_type": "code",
157 | "execution_count": 8,
158 | "metadata": {},
159 | "outputs": [
160 | {
161 | "name": "stdout",
162 | "output_type": "stream",
163 | "text": [
164 | "r = 3248825051445311210727916863346667328660788145739950405075486158747012988304000235783552321632121300395825704156105\n",
165 | "s = 19045863015172608162317729194239143865899170147418674052844195550884758407551556669873259350475778252494769103665584\n"
166 | ]
167 | }
168 | ],
169 | "source": [
170 | "(r,s)=decode_dss_signature(signature)\n",
171 | "print(\"r = %d\\ns = %d\" % (r,s) )"
172 | ]
173 | },
174 | {
175 | "cell_type": "markdown",
176 | "metadata": {},
177 | "source": [
178 | "We can verify the signature using the public key. If the signature is wrong, we get an exception"
179 | ]
180 | },
181 | {
182 | "cell_type": "code",
183 | "execution_count": 9,
184 | "metadata": {},
185 | "outputs": [
186 | {
187 | "name": "stdout",
188 | "output_type": "stream",
189 | "text": [
190 | "OK\n"
191 | ]
192 | }
193 | ],
194 | "source": [
195 | "try:\n",
196 | " public_key.verify(signature,data,ec.ECDSA(hashes.SHA256()))\n",
197 | " print(\"OK\")\n",
198 | "except:\n",
199 | " print(\"KO\")"
200 | ]
201 | },
202 | {
203 | "cell_type": "markdown",
204 | "metadata": {},
205 | "source": [
206 | "## Lab"
207 | ]
208 | },
209 | {
210 | "cell_type": "markdown",
211 | "metadata": {},
212 | "source": [
213 | "Find a classmate. One plays as Alice, the other plays as Bob.\n",
214 | "Alice and Bob generate their keys from secret numbers and have published the corresponding public key.\n",
215 | "\n",
216 | "Alice must prove to Bob that she is Alice.\n",
217 | "She derives her private key from her secret number and signs a message.\n",
218 | "Then she sends to Bob the message and the signature.\n",
219 | "Bob verifies the signature using Alice's public key.\n",
220 | "\n",
221 | "Bob proves his identity to Alice in the same way."
222 | ]
223 | },
224 | {
225 | "cell_type": "code",
226 | "execution_count": 25,
227 | "metadata": {},
228 | "outputs": [],
229 | "source": [
230 | "# Alice\n",
231 | "Alice_secret_number = 1234\n",
232 | "Alice_serialized_public_key = b'-----BEGIN PUBLIC KEY-----\\nMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEe2FShOUqdr8UOfiRMoGoEdS7PY4quCzZ\\nprCsAxK1ft1/zoRprQ4Jsxul09T4aB2hG32SVNtusdPAn8ziDFnNH4rCtVJedReL\\nURy3R3RY1EqiZ/y6ZLLo7NWdnbXWvQ7C\\n-----END PUBLIC KEY-----\\n'\n",
233 | "Alice_message = b\"I'm Alice\"\n",
234 | "\n",
235 | "# You can load the other party's public key with\n",
236 | "# remote_public_key = load_pem_public_key( serialized_public_key )"
237 | ]
238 | },
239 | {
240 | "cell_type": "code",
241 | "execution_count": 26,
242 | "metadata": {},
243 | "outputs": [],
244 | "source": [
245 | "# Bob\n",
246 | "Bob_secret_number = 4321\n",
247 | "Bob_serialized_public_key = b'-----BEGIN PUBLIC KEY-----\\nMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAENyisOoDb9lce4qW9DP+LueJUDXeCm89Y\\n5ZYW0sx50UdwMwgWWk+HMNfct+tBW9AY2jqMRCPJgyIu9BucU38JuwchT6gsZrQi\\nRJTXpndZMbKHD6j31yyaSZ2j9nGxNXkO\\n-----END PUBLIC KEY-----\\n'\n",
248 | "Bob_message = b\"I'm Bob\"\n",
249 | "\n",
250 | "# You can load the other party's public key with\n",
251 | "# remote_public_key = load_pem_public_key( serialized_public_key )"
252 | ]
253 | }
254 | ],
255 | "metadata": {
256 | "kernelspec": {
257 | "display_name": "Python 3 (ipykernel)",
258 | "language": "python",
259 | "name": "python3"
260 | },
261 | "language_info": {
262 | "codemirror_mode": {
263 | "name": "ipython",
264 | "version": 3
265 | },
266 | "file_extension": ".py",
267 | "mimetype": "text/x-python",
268 | "name": "python",
269 | "nbconvert_exporter": "python",
270 | "pygments_lexer": "ipython3",
271 | "version": "3.8.8"
272 | }
273 | },
274 | "nbformat": 4,
275 | "nbformat_minor": 1
276 | }
277 |
--------------------------------------------------------------------------------
/Hash Functions.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Some Tests with Hash Functions"
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "from binascii import hexlify\n",
17 | "from os import urandom\n",
18 | "from hashlib import sha256, shake_128\n",
19 | "import numpy as np\n",
20 | "import matplotlib.pyplot as plt"
21 | ]
22 | },
23 | {
24 | "cell_type": "markdown",
25 | "metadata": {},
26 | "source": [
27 | "# Example 1"
28 | ]
29 | },
30 | {
31 | "cell_type": "markdown",
32 | "metadata": {},
33 | "source": [
34 | "Let's hash an ASCII string with SHA256. Print the output will as a hexadecimal string"
35 | ]
36 | },
37 | {
38 | "cell_type": "code",
39 | "execution_count": null,
40 | "metadata": {},
41 | "outputs": [],
42 | "source": [
43 | "x = b\"test message\"\n",
44 | "y = sha256(x).hexdigest()\n",
45 | "y"
46 | ]
47 | },
48 | {
49 | "cell_type": "markdown",
50 | "metadata": {},
51 | "source": [
52 | "# Example 2"
53 | ]
54 | },
55 | {
56 | "cell_type": "markdown",
57 | "metadata": {},
58 | "source": [
59 | "Consider the hash SHAKE128 with output 16 bits. Generate a random digest and find a preimage. Print the number of attempts."
60 | ]
61 | },
62 | {
63 | "cell_type": "code",
64 | "execution_count": null,
65 | "metadata": {},
66 | "outputs": [],
67 | "source": [
68 | "DIGESTSIZE = 2\n",
69 | "\n",
70 | "# Define a hash function h with output size DIGESTSIZE bytes \n",
71 | "h = lambda x: shake_128(x).digest(DIGESTSIZE)\n",
72 | "\n",
73 | "# y is the target\n",
74 | "y = urandom(DIGESTSIZE)\n",
75 | "\n",
76 | "i = 0\n",
77 | "yp = None\n",
78 | "while (yp != y):\n",
79 | " # Generate a random 64 bit input\n",
80 | " xp = urandom(8)\n",
81 | " yp = h(xp)\n",
82 | " i = i + 1\n",
83 | "\n",
84 | "print(\"Attempt #{}\".format(i) )\n",
85 | "print(\"Preimage is {}\".format(hexlify(xp)) ) "
86 | ]
87 | },
88 | {
89 | "cell_type": "markdown",
90 | "metadata": {},
91 | "source": [
92 | "# Example 3"
93 | ]
94 | },
95 | {
96 | "cell_type": "markdown",
97 | "metadata": {},
98 | "source": [
99 | "Find, empirically, the average number of attempts to find a preimage to SHAKE128 with output 8 bits"
100 | ]
101 | },
102 | {
103 | "cell_type": "code",
104 | "execution_count": null,
105 | "metadata": {},
106 | "outputs": [],
107 | "source": [
108 | "DIGESTSIZE = 1\n",
109 | "num_simulations = 1000\n",
110 | "h = lambda x: shake_128(x).digest(DIGESTSIZE)\n",
111 | "\n",
112 | "def simulate(y):\n",
113 | " i = 0\n",
114 | " yp = None\n",
115 | " while (y != yp):\n",
116 | " # Generate a random 64 bit input\n",
117 | " xp = urandom(8)\n",
118 | " yp = h(xp)\n",
119 | " i = i + 1\n",
120 | " return(i) \n",
121 | "\n",
122 | "messages = [ urandom(DIGESTSIZE) for _ in range(num_simulations) ]\n",
123 | "simulations = [simulate(m) for m in messages]\n",
124 | "\n",
125 | "np.mean(simulations)"
126 | ]
127 | },
128 | {
129 | "cell_type": "code",
130 | "execution_count": null,
131 | "metadata": {},
132 | "outputs": [],
133 | "source": [
134 | "plt.hist(simulations,32);\n",
135 | "plt.xlabel('Number of attempts')\n",
136 | "plt.ylabel('Occurrences')"
137 | ]
138 | },
139 | {
140 | "cell_type": "markdown",
141 | "metadata": {},
142 | "source": [
143 | "# Example 4"
144 | ]
145 | },
146 | {
147 | "cell_type": "markdown",
148 | "metadata": {},
149 | "source": [
150 | "Find the empirical probability of finding a second preimage with $q=100$ attempts "
151 | ]
152 | },
153 | {
154 | "cell_type": "code",
155 | "execution_count": null,
156 | "metadata": {},
157 | "outputs": [],
158 | "source": [
159 | "DIGESTSIZE = 2\n",
160 | "# attempts\n",
161 | "q = 100\n",
162 | "# number of simulations\n",
163 | "num_simulations = 10000\n",
164 | "\n",
165 | "h = lambda x: shake_128(x).digest(DIGESTSIZE)\n",
166 | "\n",
167 | "def simulate(message,attempts):\n",
168 | " y = h(message)\n",
169 | " xp = [ urandom(8) for _ in range(attempts) ]\n",
170 | " yp = [ h(x) for x in xp]\n",
171 | " return ( y in yp )\n",
172 | "\n",
173 | "# generate many random messages\n",
174 | "messages = [urandom(8) for _ in range(num_simulations)]\n",
175 | "\n",
176 | "# simulate finding a second preimage\n",
177 | "simulations = [ simulate(m,q) for m in messages]\n",
178 | "\n",
179 | "# result\n",
180 | "p_succ = (sum(simulations)) / num_simulations\n",
181 | "p_theory = q / pow(2,DIGESTSIZE * 8)\n",
182 | "\n",
183 | "print(\"Simulations: p={}\".format(p_succ))\n",
184 | "print(\"Theory: p={}\".format(p_theory))"
185 | ]
186 | },
187 | {
188 | "cell_type": "markdown",
189 | "metadata": {},
190 | "source": [
191 | "# Example 5"
192 | ]
193 | },
194 | {
195 | "cell_type": "markdown",
196 | "metadata": {},
197 | "source": [
198 | "Find the empirical probability of finding a collision with q=30 attempts.\n",
199 | "Use a 16-bit hash function"
200 | ]
201 | },
202 | {
203 | "cell_type": "code",
204 | "execution_count": null,
205 | "metadata": {},
206 | "outputs": [],
207 | "source": [
208 | "DIGESTSIZE = 2\n",
209 | "# attempts\n",
210 | "q = 30\n",
211 | "# number of simulations\n",
212 | "num_simulations = 10000\n",
213 | "\n",
214 | "h = lambda x: shake_128(x).digest(DIGESTSIZE)\n",
215 | "\n",
216 | "def simulate(attempts):\n",
217 | " xp = [ urandom(8) for _ in range(attempts) ]\n",
218 | " yp = [ h(x) for x in xp]\n",
219 | " # remove unique items\n",
220 | " ys = set(yp)\n",
221 | " # if they are the same, there were no duplicates \n",
222 | " return (len(ys) != len(yp))\n",
223 | "\n",
224 | "# simulate finding a collision\n",
225 | "simulations = [ simulate(q) for _ in range(num_simulations)]\n",
226 | "# result\n",
227 | "p_succ = (sum(simulations)) / num_simulations\n",
228 | "p_theory = 1-np.exp(-q**2 / pow(2,DIGESTSIZE*8+1))\n",
229 | "\n",
230 | "print(\"Simulations: p={}\".format(p_succ))\n",
231 | "print(\"Theory: p={}\".format(p_theory))"
232 | ]
233 | },
234 | {
235 | "cell_type": "markdown",
236 | "metadata": {},
237 | "source": [
238 | "# Lab Work\n",
239 | "\n",
240 | "Work in pairs. One is Alice, one is Bob.\n",
241 | "\n",
242 | "Use SHAKE128 with 8 bits output.\n",
243 | "\n",
244 | "Alice generates a random input and sends it to Bob. Bob finds a second preimage and sends it to Alice.\n",
245 | "Alice verifies that the second preimage is correct.\n",
246 | "\n",
247 | "How many attempts did Bob make?\n",
248 | "\n",
249 | "Now swap your roles and use SHAKE128 with 16 bits of output."
250 | ]
251 | },
252 | {
253 | "cell_type": "markdown",
254 | "metadata": {},
255 | "source": [
256 | "# Challenge"
257 | ]
258 | },
259 | {
260 | "cell_type": "markdown",
261 | "metadata": {},
262 | "source": [
263 | "For this challenge use the hash function SHAKE128 with 1 byte of output. Your goal it to find a second preimage for the following input. Measure the time it takes, then increase the output size by one byte and repeat. Plot your measurements in a graph."
264 | ]
265 | },
266 | {
267 | "cell_type": "code",
268 | "execution_count": null,
269 | "metadata": {},
270 | "outputs": [],
271 | "source": [
272 | "input_string = b'The frog jumped into the pond'"
273 | ]
274 | }
275 | ],
276 | "metadata": {
277 | "anaconda-cloud": {},
278 | "kernelspec": {
279 | "display_name": "Python 3 (ipykernel)",
280 | "language": "python",
281 | "name": "python3"
282 | },
283 | "language_info": {
284 | "codemirror_mode": {
285 | "name": "ipython",
286 | "version": 3
287 | },
288 | "file_extension": ".py",
289 | "mimetype": "text/x-python",
290 | "name": "python",
291 | "nbconvert_exporter": "python",
292 | "pygments_lexer": "ipython3",
293 | "version": "3.11.7"
294 | }
295 | },
296 | "nbformat": 4,
297 | "nbformat_minor": 4
298 | }
299 |
--------------------------------------------------------------------------------
/Information-Theoretic Security.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Information-Theoretic Security (examples and exercises)"
8 | ]
9 | },
10 | {
11 | "cell_type": "markdown",
12 | "metadata": {},
13 | "source": [
14 | "## Definitions of Information Entropy"
15 | ]
16 | },
17 | {
18 | "cell_type": "markdown",
19 | "metadata": {},
20 | "source": [
21 | "### Source Entropy\n",
22 | "\n",
23 | "Given a message $m$ taken from a set of messages $\\{m_1, \\dots, m_N\\}$ with probabilities $p(m_i)\\ 1\\leq i \\leq N$, the source entropy is\n",
24 | "\n",
25 | "$H(m) = -\\sum_{i=1}^N p_i \\log_2 p_i$\n",
26 | "\n",
27 | "Source entropy measures the minimum number of bits necessary to encode the source messages."
28 | ]
29 | },
30 | {
31 | "cell_type": "markdown",
32 | "metadata": {},
33 | "source": [
34 | "### Joint Entropy\n",
35 | "\n",
36 | "Given a message $m$ taken from a set of messages $\\{m_i\\}$ with probabilities $p(m_i)$ and a message $c$ taken from a set of messages $\\{c_j\\}$ with probabilities $p(c_j)$ and joint probabilities $p(m_i,c_j)$, the joint entropy is\n",
37 | "\n",
38 | "$H(m,c) = - \\sum_{i,j} p(m_i,c_j) \\log_2 p(m_i,c_j)$"
39 | ]
40 | },
41 | {
42 | "cell_type": "markdown",
43 | "metadata": {},
44 | "source": [
45 | "### Conditional Entropy\n",
46 | "\n",
47 | "Given a message $m$ taken from a set of messages $\\{m_i\\}$ with probabilities $p(m_i)$ and a ciphertext $c$ taken from a set of messages $\\{c_j\\}$ with probabilities $p(c_j)$ and joint probabilities $p(m_i,c_j)$, the conditional entropy is\n",
48 | "\n",
49 | "$H(c|m) = \\sum_i H(c|m_i) \\Pr[m_i]$"
50 | ]
51 | },
52 | {
53 | "cell_type": "markdown",
54 | "metadata": {},
55 | "source": [
56 | "### Chain Rule\n",
57 | "\n",
58 | "$H(m,c) = H(m) + H(c|m) = H(c) + H(m|c)$"
59 | ]
60 | },
61 | {
62 | "cell_type": "markdown",
63 | "metadata": {},
64 | "source": [
65 | "### Bayes' Theorem\n",
66 | "\n",
67 | "$H(m|c) = H(c|m) - H(c) + H(m)$"
68 | ]
69 | },
70 | {
71 | "cell_type": "markdown",
72 | "metadata": {},
73 | "source": [
74 | "### Mutual Information\n",
75 | "\n",
76 | "$I(m;c) = H(m)-H(m|c) = H(c)-H(c|m)$\n",
77 | "\n",
78 | "Mutual information is equal to zero if and only if the message and the ciphertext are independent."
79 | ]
80 | },
81 | {
82 | "cell_type": "markdown",
83 | "metadata": {},
84 | "source": [
85 | "## Exercise 1\n",
86 | "\n",
87 | "Assume that the message space is $M = \\{\\texttt{A}, \\texttt{Z} \\}$.\n",
88 | "Alice chooses $m=\\texttt{A}$ with probability 0.7 and $m=\\texttt{Z}$ with probability 0.3. Alice encrypts the message with some random key.\n",
89 | "\n",
90 | "Eve, an eavesdropper, sees $c=\\texttt{B}$. What can she say about the plaintext?\n",
91 | "What is $I(m;c)$?"
92 | ]
93 | },
94 | {
95 | "cell_type": "markdown",
96 | "metadata": {},
97 | "source": [
98 | "**Solution (analytical)**\n",
99 | "\n",
100 | "The entropy of the message source is:\n",
101 | "\n",
102 | "$H(m) =\n",
103 | "- \\Pr[m=\\texttt{A}] \\log_2 \\Pr[m=\\texttt{A}]\n",
104 | "- \\Pr[m=\\texttt{Z}] \\log_2 \\Pr[m=\\texttt{Z}]\t\n",
105 | "= 0.88\\,\\mathrm{bit}$\n",
106 | "\n",
107 | "Given a plaintext, all ciphertexts are equally likely, so \n",
108 | "\n",
109 | "$H(c|m) = 26 \\times \\frac{1}{26}\\log_2 26 = 4.7\\,\\mathrm{bit}$\n",
110 | "\n",
111 | "We already know that\n",
112 | "\n",
113 | "$\\Pr[c=\\texttt{A}]=\\dots=\\Pr[c=\\texttt{Z}]=1/26$\n",
114 | "\n",
115 | "thus $H(c)=4.7\\,\\mathrm{bit}$.\n",
116 | "\n",
117 | "Therefore:\n",
118 | "\n",
119 | "$I(m;c) = H(c) - H(c|m) = 0$\n",
120 | "\n",
121 | "No information is learned."
122 | ]
123 | },
124 | {
125 | "cell_type": "markdown",
126 | "metadata": {},
127 | "source": [
128 | "**Solution (empirical)**"
129 | ]
130 | },
131 | {
132 | "cell_type": "code",
133 | "execution_count": 1,
134 | "metadata": {},
135 | "outputs": [],
136 | "source": [
137 | "from random import random, randint\n",
138 | "import numpy as np"
139 | ]
140 | },
141 | {
142 | "cell_type": "code",
143 | "execution_count": 3,
144 | "metadata": {},
145 | "outputs": [],
146 | "source": [
147 | "# calculates the entropy of a list of elements\n",
148 | "# builds the empyrical pdf of the list\n",
149 | "# then applies the definition\n",
150 | "def entropy_of_list(l):\n",
151 | " histogram = {x:(l.count(x)+0.0)/len(l) for x in l}\n",
152 | " return sum([-x*log(x,2) for x in histogram.values()])"
153 | ]
154 | },
155 | {
156 | "cell_type": "code",
157 | "execution_count": null,
158 | "metadata": {},
159 | "outputs": [],
160 | "source": [
161 | "# Instantiate a shift cipher over the alphabet\n",
162 | "S = ShiftCryptosystem(AlphabeticStrings());\n",
163 | "\n",
164 | "# Define the random key generator\n",
165 | "def keygen():\n",
166 | " return randint(0,25)"
167 | ]
168 | },
169 | {
170 | "cell_type": "code",
171 | "execution_count": 2,
172 | "metadata": {},
173 | "outputs": [],
174 | "source": [
175 | "# message source\n",
176 | "def message1():\n",
177 | " if random()<=0.7:\n",
178 | " return 'A'\n",
179 | " else:\n",
180 | " return 'Z'"
181 | ]
182 | },
183 | {
184 | "cell_type": "code",
185 | "execution_count": 11,
186 | "metadata": {},
187 | "outputs": [
188 | {
189 | "name": "stdout",
190 | "output_type": "stream",
191 | "text": [
192 | "Empirical Entropy of source is: 0.893173458377857\n"
193 | ]
194 | }
195 | ],
196 | "source": [
197 | "# generate several random messages \n",
198 | "m = [S.encoding(message1()) for i in range(1000)]\n",
199 | "\n",
200 | "# print empirical entropy of the message source\n",
201 | "print \"Empirical Entropy of source is:\", entropy_of_list(m)"
202 | ]
203 | },
204 | {
205 | "cell_type": "code",
206 | "execution_count": 12,
207 | "metadata": {},
208 | "outputs": [
209 | {
210 | "name": "stdout",
211 | "output_type": "stream",
212 | "text": [
213 | "Empirical Entropy of ciphertext is: 4.68926722828748\n"
214 | ]
215 | }
216 | ],
217 | "source": [
218 | "# Encrypt each message with a different random key\n",
219 | "c = [ S.enciphering( keygen() , x ) for x in m ]\n",
220 | "\n",
221 | "print \"Empirical Entropy of ciphertext is:\", entropy_of_list(c)"
222 | ]
223 | },
224 | {
225 | "cell_type": "markdown",
226 | "metadata": {},
227 | "source": [
228 | "## Exercise 2\n",
229 | "\n",
230 | "Assume that $\\Pr[m=\\texttt{kim}]=0.5$, $\\Pr[m=\\texttt{ann}]=0.2$, and $\\Pr[m=\\texttt{boo}]=0.3$.\n",
231 | "\n",
232 | "What is $I(m;c)$?"
233 | ]
234 | },
235 | {
236 | "cell_type": "markdown",
237 | "metadata": {},
238 | "source": [
239 | "**Solution (analytical)** \n",
240 | "Analogous calculations can be done using information entropy.\n",
241 | "The entropy of the message source is:\n",
242 | "\n",
243 | "$H(m) = 1.49 bit$\n",
244 | "\n",
245 | "Ciphertexts are not equally likely. There are only $26+26=52$ different CTs, half of which obtained from $\\texttt{kim}$ and half from $\\texttt{ann}$ and $\\texttt{boo}$.\n",
246 | "\n",
247 | "$H(c) = - 52 \\frac{1}{52}\\log_2\\frac{1}{52} = 5.7 bit$\n",
248 | "\n",
249 | "Given a plaintex, all ciphertexts are equally likely:\n",
250 | "$H(c|m) = 4.7 bit$.\n",
251 | "\n",
252 | "$I(m;c) = H(c) -H(c|m) = 1 bit$\n",
253 | "meaning that knowledge of $c$ gives us 1 bit of information.\n",
254 | "\n",
255 | "What does it mean that mutual information is 1 bit? It means that there exists an agorithm that can answer a yes/no question about the plaintext by just looking to the ciphertext.\n",
256 | "\n",
257 | "This does not tell us what is the algorithm to obtain this bit. Neither whether this algorithm is efficient. It only tells us that this algorithm exists.\n",
258 | "The following is just an example:\n",
259 | "\n",
260 | "```\n",
261 | "def plaintext_is_kim(ciphertext):\n",
262 | " if last two letters of ciphertext are the same:\n",
263 | " return false # plaintext is not kim\n",
264 | " else\n",
265 | " return true # plaintext is kim\n",
266 | " end if\n",
267 | "```"
268 | ]
269 | },
270 | {
271 | "cell_type": "markdown",
272 | "metadata": {},
273 | "source": [
274 | "**Solution (empirical)**"
275 | ]
276 | },
277 | {
278 | "cell_type": "code",
279 | "execution_count": 14,
280 | "metadata": {},
281 | "outputs": [],
282 | "source": [
283 | "# generate random three letter messages\n",
284 | "def message2():\n",
285 | " r = random() \n",
286 | " if r <= 0.5:\n",
287 | " return 'KIM'\n",
288 | " if r <= 0.7:\n",
289 | " return 'ANN'\n",
290 | " else:\n",
291 | " return 'BOO'"
292 | ]
293 | },
294 | {
295 | "cell_type": "code",
296 | "execution_count": 15,
297 | "metadata": {},
298 | "outputs": [
299 | {
300 | "name": "stdout",
301 | "output_type": "stream",
302 | "text": [
303 | "Empirical Entropy of source is: 1.47717700758957\n"
304 | ]
305 | }
306 | ],
307 | "source": [
308 | "# generate random messages \n",
309 | "m = [S.encoding(message2()) for i in range(1000)]\n",
310 | "\n",
311 | "# print empirical entropy of the message source\n",
312 | "print \"Empirical Entropy of source is:\", entropy_of_list(m)"
313 | ]
314 | },
315 | {
316 | "cell_type": "code",
317 | "execution_count": 16,
318 | "metadata": {},
319 | "outputs": [
320 | {
321 | "name": "stdout",
322 | "output_type": "stream",
323 | "text": [
324 | "Empirical Entropy of ciphertext is: 5.67313984293835\n"
325 | ]
326 | }
327 | ],
328 | "source": [
329 | "# Encrypt each message with a random key\n",
330 | "c=[S.enciphering( keygen(), x) for x in m]\n",
331 | "\n",
332 | "print \"Empirical Entropy of ciphertext is:\", entropy_of_list(c)"
333 | ]
334 | },
335 | {
336 | "cell_type": "markdown",
337 | "metadata": {},
338 | "source": [
339 | "## Exercise 3\n",
340 | "\n",
341 | "Consider a Vigènere cipher. Messages are 4-character sequences of letters. Passwords are $n$-character long.\n",
342 | "\n",
343 | "Assume that there are three possible messages, with different probabilities.\n",
344 | "\n",
345 | "| Message | Probability |\n",
346 | "|---|---|\n",
347 | "| $m_1$ = BEBA | 0.5 |\n",
348 | "| $m_2$ = DEDA | 0.3 |\n",
349 | "| $m_3$ = CFCB | 0.2 |\n",
350 | "\n",
351 | "1. Calculate the entropy of the source.\n",
352 | "2. Calculate the entropy of the key with $n=1,2,4$.\n",
353 | "3. Calculate the entropy of the ciphertext with $n=1,2,4$.\n",
354 | "4. Calculate the information leak of the ciphertext with $n=1,2,4$\n",
355 | "5. Is the cipher of this exercise perfectly secret?"
356 | ]
357 | },
358 | {
359 | "cell_type": "markdown",
360 | "metadata": {},
361 | "source": [
362 | "### Solution\n",
363 | "\n",
364 | "#### Part 1\n",
365 | "\n",
366 | "$H(M) = -0.5\\log_2 0.5 -0.3\\log_2 0.3 -0.2\\log_2 0.2 = 1.48$\n",
367 | "\n",
368 | "#### Part 2\n",
369 | "\n",
370 | "| $n$ | $H(K)$ |\n",
371 | "| --- | ------ |\n",
372 | "| 1 | 4.7 |\n",
373 | "| 2 | 9.4 |\n",
374 | "| 4 | 18.8 |\n",
375 | "\n",
376 | "\n",
377 | "#### Part 3\n",
378 | "\n",
379 | "Let call $C_i$ the set of possible ciphertexts for message $m_i$.\n",
380 | "\n",
381 | "With $n=1$, we have\n",
382 | "* $C_1 = \\{ \\text{BEBA}, \\text{CFCB}, \\text{DGDC}, \\dots \\}$\n",
383 | "* $C_2 = \\{ \\text{DEDA}, \\text{EFEB}, \\text{FGFB}, \\dots \\}$\n",
384 | "* $C_3 = \\{ \\text{CFCB}, \\text{DGDC}, \\text{EHED}, \\dots \\}$\n",
385 | "\n",
386 | "So $C_1 = C_3$, while $C_2$ is distinct. Thus, we have $2\\times26=52$ ciphertexts. The first set has probability $0.5+0.2=0.7$. The second set has probability $0.3$.\n",
387 | "\n",
388 | "$H(C)=\n",
389 | " -26\\times 0.7/26\\log_2 0.7/26\n",
390 | " -26\\times 0.3/26\\log_2 0.3/26\n",
391 | " = 5.58\n",
392 | "$\n",
393 | "\n",
394 | "With $n=2$, we have again $C_1 = C_2 = C_3$. In fact, the key $(2,0)$ can map BEBA into DEDA, while the key $(1,1)$ can map BEBA into CFCB. Consequently all the messages generate the same $26^2=676$ ciphertexts.\n",
395 | "\n",
396 | "$H(C)= -676 / 676 \\log_2(1/676)=9.4$\n",
397 | "\n",
398 | "With $n=4$, we have $C_1 = C_2 = C_3$. Thus, we have $26^4=456976$ equally likely ciphertexts.\n",
399 | "\n",
400 | "$H(C)= 26^4 / 26^4 \\log_2(1/26^4)=18.8$\n",
401 | "\n",
402 | "#### Part 4\n",
403 | "\n",
404 | "With $n=1$\n",
405 | "\n",
406 | "$H(C|M)=H(C_1)\\Pr(m_1) + H(C_2)\\Pr(m_2) + H(C_3)\\Pr(m_3)= 4.7$\n",
407 | "\n",
408 | "Then\n",
409 | "$\n",
410 | "\tI(M;C) =\n",
411 | "\tH(C)-H(C|M) = 5.58 - 4.7 = 0.88\n",
412 | "$\n",
413 | "\n",
414 | "With $n=2$\n",
415 | "\n",
416 | "$\n",
417 | "\tH(C|M)=H(C_1)\\Pr(m_1) + H(C_2)\\Pr(m_2+m_3)= 9.4\n",
418 | "$\n",
419 | "\n",
420 | "Then\n",
421 | "$\n",
422 | "\tI(M;C) =\n",
423 | "\tH(C)-H(C|M) = 9.4-9.4 = 0\n",
424 | "$\n",
425 | "\n",
426 | "With $n=4$\n",
427 | "\n",
428 | "$\n",
429 | "\tH(C|M)=H(C_1)\\Pr(m_1+m_2+m_3)= 18.8\n",
430 | "$\n",
431 | "\n",
432 | "Then\n",
433 | "$\n",
434 | "\tI(M;C) =\n",
435 | "\tH(C)-H(C|M) = 18.8-18.8=0\n",
436 | "$\n",
437 | "\n",
438 | "#### Part 5\n",
439 | "If these three are the only possible messages, then with $n=2$ and $n=4$ we have perfect secrecy."
440 | ]
441 | },
442 | {
443 | "cell_type": "code",
444 | "execution_count": null,
445 | "metadata": {},
446 | "outputs": [],
447 | "source": []
448 | }
449 | ],
450 | "metadata": {
451 | "kernelspec": {
452 | "display_name": "Python 3 (ipykernel)",
453 | "language": "python",
454 | "name": "python3"
455 | },
456 | "language_info": {
457 | "codemirror_mode": {
458 | "name": "ipython",
459 | "version": 3
460 | },
461 | "file_extension": ".py",
462 | "mimetype": "text/x-python",
463 | "name": "python",
464 | "nbconvert_exporter": "python",
465 | "pygments_lexer": "ipython3",
466 | "version": "3.9.7"
467 | }
468 | },
469 | "nbformat": 4,
470 | "nbformat_minor": 2
471 | }
472 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Network Security and Cryptography course page
2 |
3 | Currently some notebooks require the python3 kernel and some require the sagemath kernel
4 |
5 | Notebooks in this collection:
6 | 1. Classic Ciphers [](https://colab.research.google.com/github/gverticale/network-security-and-cryptography/blob/master/Classic%20ciphers.ipynb)
7 | 2. Secret Sharing [](https://colab.research.google.com/github/gverticale/network-security-and-cryptography/blob/master/Secret%20Sharing.ipynb)
8 | 3. Secret Sharing (Galois) [](https://colab.research.google.com/github/gverticale/network-security-and-cryptography/blob/master/Secret%20Sharing%20(gf).ipynb)
9 | 4. Hash Functions [](https://colab.research.google.com/github/gverticale/network-security-and-cryptography/blob/master/Hash%20Functions.ipynb)
10 | 5. Stream Ciphers [](https://colab.research.google.com/github/gverticale/network-security-and-cryptography/blob/master/StreamCiphers.ipynb)
11 | 6. Symmetric Ciphers [](https://colab.research.google.com/github/gverticale/network-security-and-cryptography/blob/master/Symmetric.ipynb)
12 | 7. RSA [](https://colab.research.google.com/github/gverticale/network-security-and-cryptography/blob/master/RSA.ipynb)
13 | 8. Legacy DSA [](https://colab.research.google.com/github/gverticale/network-security-and-cryptography/blob/master/DSA.ipynb)
14 | 9. Diffie-Hellman [](https://colab.research.google.com/github/gverticale/network-security-and-cryptography/blob/master/DHKE.ipynb)
15 | 8. Elliptic Curves [](https://colab.research.google.com/github/gverticale/network-security-and-cryptography/blob/master/Elliptic%20Curves.ipynb)
16 |
17 | Open this repository:
18 | [](https://colab.research.google.com/github/gverticale/network-security-and-cryptography/blob/master)
19 | [](https://studiolab.sagemaker.aws/import/github/gverticale/network-security-and-cryptography/blob/master)
20 | [](https://mybinder.org/v2/gh/gverticale/network-security-and-cryptography/HEAD)
21 |
--------------------------------------------------------------------------------
/RSA.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Playing with RSA"
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "from math import log2, floor, isqrt\n",
17 | "from timeit import timeit\n",
18 | "from sympy import randprime, nextprime\n",
19 | "\n",
20 | "from cryptography.hazmat.primitives.asymmetric import rsa, padding\n",
21 | "from cryptography.hazmat.primitives import hashes, serialization"
22 | ]
23 | },
24 | {
25 | "cell_type": "markdown",
26 | "metadata": {},
27 | "source": [
28 | "## What happens if p and q are too close?"
29 | ]
30 | },
31 | {
32 | "cell_type": "code",
33 | "execution_count": null,
34 | "metadata": {},
35 | "outputs": [],
36 | "source": [
37 | "# p = next_prime(2^512)\n",
38 | "p = randprime(2**511, 2**512)\n",
39 | "p"
40 | ]
41 | },
42 | {
43 | "cell_type": "code",
44 | "execution_count": null,
45 | "metadata": {},
46 | "outputs": [],
47 | "source": [
48 | "q=nextprime(p)\n",
49 | "q"
50 | ]
51 | },
52 | {
53 | "cell_type": "code",
54 | "execution_count": null,
55 | "metadata": {},
56 | "outputs": [],
57 | "source": [
58 | "n = p * q\n",
59 | "n"
60 | ]
61 | },
62 | {
63 | "cell_type": "code",
64 | "execution_count": null,
65 | "metadata": {},
66 | "outputs": [],
67 | "source": [
68 | "# n has 1024 bit\n",
69 | "log2(n)"
70 | ]
71 | },
72 | {
73 | "cell_type": "code",
74 | "execution_count": null,
75 | "metadata": {},
76 | "outputs": [],
77 | "source": [
78 | "# We start from the square root and look for the next prime\n",
79 | "# isqrt is the integer part of the square root\n",
80 | "t = isqrt(n)\n",
81 | "t"
82 | ]
83 | },
84 | {
85 | "cell_type": "code",
86 | "execution_count": null,
87 | "metadata": {},
88 | "outputs": [],
89 | "source": [
90 | "nextprime(t)"
91 | ]
92 | },
93 | {
94 | "cell_type": "code",
95 | "execution_count": null,
96 | "metadata": {},
97 | "outputs": [],
98 | "source": [
99 | "# Compare with q\n",
100 | "q"
101 | ]
102 | },
103 | {
104 | "cell_type": "markdown",
105 | "metadata": {},
106 | "source": [
107 | "## How long does it take to generate a key?"
108 | ]
109 | },
110 | {
111 | "cell_type": "code",
112 | "execution_count": null,
113 | "metadata": {},
114 | "outputs": [],
115 | "source": [
116 | "def gen():\n",
117 | " return rsa.generate_private_key(\n",
118 | " public_exponent=65537,\n",
119 | " key_size=2048\n",
120 | " )"
121 | ]
122 | },
123 | {
124 | "cell_type": "code",
125 | "execution_count": null,
126 | "metadata": {},
127 | "outputs": [],
128 | "source": [
129 | "timeit(gen, number = 100)"
130 | ]
131 | },
132 | {
133 | "cell_type": "markdown",
134 | "metadata": {},
135 | "source": [
136 | "## What happens if the exponent is too low?"
137 | ]
138 | },
139 | {
140 | "cell_type": "code",
141 | "execution_count": null,
142 | "metadata": {},
143 | "outputs": [],
144 | "source": [
145 | "private_key = rsa.generate_private_key(\n",
146 | " public_exponent=3,\n",
147 | " key_size=1024\n",
148 | ")\n",
149 | "public_key = private_key.public_key()\n",
150 | "\n",
151 | "e = public_key.public_numbers().e\n",
152 | "n = public_key.public_numbers().n\n",
153 | "print(\"e = {}\\nn = {}\".format(e,n))"
154 | ]
155 | },
156 | {
157 | "cell_type": "code",
158 | "execution_count": null,
159 | "metadata": {},
160 | "outputs": [],
161 | "source": [
162 | "message = b\"OK\"\n",
163 | "\n",
164 | "m = int.from_bytes(message,\"big\")\n",
165 | "c_small = pow(m,e,n)\n",
166 | "\n",
167 | "print(\"m = {}\\nc = {}\".format(m,c_small))"
168 | ]
169 | },
170 | {
171 | "cell_type": "code",
172 | "execution_count": null,
173 | "metadata": {},
174 | "outputs": [],
175 | "source": [
176 | "# Can we find the message?\n",
177 | "# If the message is small, the modulo is not effective and we can just take the e-th root\n",
178 | "pow(c_small,1/3)"
179 | ]
180 | },
181 | {
182 | "cell_type": "code",
183 | "execution_count": null,
184 | "metadata": {},
185 | "outputs": [],
186 | "source": [
187 | "# If we use padding the problem is solved\n",
188 | "c = public_key.encrypt(\n",
189 | " message,\n",
190 | " padding.OAEP(\n",
191 | " mgf=padding.MGF1( algorithm=hashes.SHA256() ),\n",
192 | " algorithm=hashes.SHA256(),\n",
193 | " label=None\n",
194 | " )\n",
195 | ")\n",
196 | "print(\"c = {:d}\".format(int.from_bytes(c,\"big\")))"
197 | ]
198 | },
199 | {
200 | "cell_type": "code",
201 | "execution_count": null,
202 | "metadata": {},
203 | "outputs": [],
204 | "source": [
205 | "private_key.decrypt(\n",
206 | " c,\n",
207 | " padding.OAEP(\n",
208 | " mgf=padding.MGF1(algorithm=hashes.SHA256()),\n",
209 | " algorithm=hashes.SHA256(),\n",
210 | " label=None\n",
211 | " )\n",
212 | ")"
213 | ]
214 | },
215 | {
216 | "cell_type": "markdown",
217 | "metadata": {},
218 | "source": [
219 | "## Signature\n",
220 | "\n",
221 | "The key generation is the same as encryption, but we want a fresh key"
222 | ]
223 | },
224 | {
225 | "cell_type": "code",
226 | "execution_count": null,
227 | "metadata": {},
228 | "outputs": [],
229 | "source": [
230 | "private_key = rsa.generate_private_key(\n",
231 | " public_exponent=65537,\n",
232 | " key_size=4096\n",
233 | ")\n",
234 | "public_key = private_key.public_key()"
235 | ]
236 | },
237 | {
238 | "cell_type": "code",
239 | "execution_count": null,
240 | "metadata": {},
241 | "outputs": [],
242 | "source": [
243 | "message = b\"A message I want to sign\"\n",
244 | "signature = private_key.sign(\n",
245 | " message,\n",
246 | " padding.PSS(\n",
247 | " mgf=padding.MGF1( hashes.SHA256() ),\n",
248 | " salt_length=padding.PSS.MAX_LENGTH\n",
249 | " ),\n",
250 | " hashes.SHA256()\n",
251 | ")"
252 | ]
253 | },
254 | {
255 | "cell_type": "code",
256 | "execution_count": null,
257 | "metadata": {},
258 | "outputs": [],
259 | "source": [
260 | "try:\n",
261 | " public_key.verify(\n",
262 | " signature,\n",
263 | " message,\n",
264 | " padding.PSS(\n",
265 | " mgf=padding.MGF1( hashes.SHA256() ),\n",
266 | " salt_length=padding.PSS.MAX_LENGTH\n",
267 | " ),\n",
268 | " hashes.SHA256()\n",
269 | " )\n",
270 | " print(\"OK\")\n",
271 | "except:\n",
272 | " print(\"KO\")"
273 | ]
274 | },
275 | {
276 | "cell_type": "code",
277 | "execution_count": null,
278 | "metadata": {},
279 | "outputs": [],
280 | "source": [
281 | "message = b\"Not the real message\"\n",
282 | "try:\n",
283 | " public_key.verify(\n",
284 | " signature,\n",
285 | " message,\n",
286 | " padding.PSS(\n",
287 | " mgf=padding.MGF1( hashes.SHA256() ),\n",
288 | " salt_length=padding.PSS.MAX_LENGTH\n",
289 | " ),\n",
290 | " hashes.SHA256()\n",
291 | " )\n",
292 | " print(\"OK\")\n",
293 | "except:\n",
294 | " print(\"KO\")"
295 | ]
296 | },
297 | {
298 | "cell_type": "markdown",
299 | "metadata": {},
300 | "source": [
301 | "## How to export and import the public key"
302 | ]
303 | },
304 | {
305 | "cell_type": "code",
306 | "execution_count": null,
307 | "metadata": {},
308 | "outputs": [],
309 | "source": [
310 | "private_key = rsa.generate_private_key(\n",
311 | " public_exponent=65537,\n",
312 | " key_size=4096\n",
313 | ")\n",
314 | "public_key = private_key.public_key()"
315 | ]
316 | },
317 | {
318 | "cell_type": "code",
319 | "execution_count": null,
320 | "metadata": {},
321 | "outputs": [],
322 | "source": [
323 | "#Export public key\n",
324 | "pem = public_key.public_bytes(\n",
325 | " encoding=serialization.Encoding.PEM,\n",
326 | " format=serialization.PublicFormat.SubjectPublicKeyInfo\n",
327 | ")\n",
328 | "pem"
329 | ]
330 | },
331 | {
332 | "cell_type": "code",
333 | "execution_count": null,
334 | "metadata": {},
335 | "outputs": [],
336 | "source": [
337 | "#Import public key\n",
338 | "pem = b'-----BEGIN PUBLIC KEY-----\\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAu/Av7jMZ66oaSWZXHs+J\\nWlWcL2c4TjWDVS0qVCAquQRNY/DPNO7SWP6rIdPybKtOdPLf0L6mjHZ374UzxuU4\\nN4dCanKeVAz7spf6JqTJCxL9mao7cD83hRIhXYNp1ljNJKw8E9U/X8m3uFOnEiZb\\nDswPEudBQqu98zKUDOlIZl2/UPk6CO5ocs384A5sXVHUB7a1rb3Fw9x9HEZosm7o\\nx/hzskU11OvVux2nQxIeiYdIimRGKmHiSMbWY5LI5QEn8aPcUwK2e+ZUa8o9khQr\\n5EpzBZBUzxk7UC3iWDG+pmGkI0AHdExir8nRuhQHIm/TxTl2aLwZOnDjs6gOzEn5\\npsHhEsx8wYktnQnZV4ix59SPbhxhW9mo3b4F+04k7/JPpF/WaWhK+GGTRtZFs19A\\nrF5p+EIoCr9PEaL5nhDTKZm9Zl73Bor/VyZxi6DpBU/NVdWV6B1kgEoU/yvR0JM6\\nMisBQQwxzJtNs/P0qkSbK+KzS37ANadETktVBRYUl213ihY/z0RrYoA/dguHWYYV\\nbONHaBAb0HDIx0dk26RnjXetY06bYHF8WMhWE9YmvwUoz+9Fy6Yis6Xw+2u37tR3\\nHxyVcRdKq4kavYaoBRTGyFf5iz1AOPVTJzHOGkLt+oisBwQoH09DiZL4sZ2YA4lE\\nfcD0yRbK6We+xdN+aYI35jUCAwEAAQ==\\n-----END PUBLIC KEY-----\\n'\n",
339 | "rsa_public_key = serialization.load_pem_public_key(pem)"
340 | ]
341 | },
342 | {
343 | "cell_type": "code",
344 | "execution_count": null,
345 | "metadata": {},
346 | "outputs": [],
347 | "source": []
348 | },
349 | {
350 | "cell_type": "code",
351 | "execution_count": null,
352 | "metadata": {},
353 | "outputs": [],
354 | "source": []
355 | },
356 | {
357 | "cell_type": "markdown",
358 | "metadata": {},
359 | "source": [
360 | "# Laboratory"
361 | ]
362 | },
363 | {
364 | "cell_type": "markdown",
365 | "metadata": {},
366 | "source": [
367 | "1. Measure the key generation time and the signature time for key sizes ranging from 512 to 4096 bits. Plot a graph."
368 | ]
369 | },
370 | {
371 | "cell_type": "markdown",
372 | "metadata": {},
373 | "source": [
374 | "2. The following is my public key. Verify my message \"Hallo class!\""
375 | ]
376 | },
377 | {
378 | "cell_type": "code",
379 | "execution_count": null,
380 | "metadata": {},
381 | "outputs": [],
382 | "source": [
383 | "# My public key\n",
384 | "b'-----BEGIN PUBLIC KEY-----\\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA40GwUqIGKVgJ3aDjyeuh\\n+IjgAYS7ZIUDmWF6zCA6/1ybbjkp3Hj6n7MYyN2VajK88Qc1EQVKiDxpnbMpc2bE\\nhrC+ElyEoI+Vy5R6CVQ8UtKEFwQ+dFgcMOrsw/4v1lj0RyQpo2yzwXY8aXqpraKG\\nyyKEu+gbmUpjKJODAyyPey8xM3LyWlzB21QwVYO+6H9kQ48engFJMBT2di5gmlZv\\ngNOKfdA+EWi3biblQlOPUSTtvMNzIlH1XIO27t21yQK3yTLB6+uZjjFe5s5h7uTU\\nRdbrOksTD+4DGzFAa8o7Uom34BRZJ0zUIcZVBqwvX/8NA7pSRoL9Q8kq0hCcnZak\\n2fgRoAK26nBzO1BcsvrnfHwr2u/lg/5Sj86d9mFRCIfAzEXPm+1Gf3oBzfxZzgEs\\nV4O1IjRmI8pul0M77rWoC7NCodZk5VbIniEY3FOKajsB1WVlZF47EuwqwkDekZBN\\nSJpPAWuModDBwTakBCznNsFFrgIS36DVtEYIgCdQA7n444t7qu3CmdktCgD+MruB\\n5Qe+8Qcn6aLlEyYwykj8vfaI06ztdCDuIdB7aeWAqb22luXxHgNGuIIGHPsOuUHF\\nJqLJjFBTf8gQKhv6ryIEeACYvDjWuN9xbvzRhM8IFIE5yw6xUuMbrhSfJYbNATU8\\naq2/Ut7ZungeWwW3TILiW1ECAwEAAQ==\\n-----END PUBLIC KEY-----\\n'"
385 | ]
386 | },
387 | {
388 | "cell_type": "code",
389 | "execution_count": null,
390 | "metadata": {},
391 | "outputs": [],
392 | "source": [
393 | "# The signature of my message \"Hallo class!\"\n",
394 | "b'}\\xf3\\x0b\\xa3\\xda\\xd4a\\xe0@p\\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0\\x19\\x92~\\x19?]\\x15\\xf3\"\\xdc\\x9876\\x8f\\x8a\\xca\\\\\\x153d\\xb6\\xab:\\xc8\\xec)Q\\xcb*\\xac\\x92\\xc3\\x06\\xe9A\\x92\\x95\\x1a\\xae\\xcf\\xf5\\x95<6\\x94n\\xf9\\xd8_\\xbf\\x05\\xc4T\\xc3\\xed\\xaf\\xf9IK\\x8e\\x16B\\x95\\x15\\xdd\\x8a\\xb0V\\xa8^\\xfd\\x06:\\x08)\\xcff\\xe9uY\\xee\\xad)\\x07S}\\x9b\\xb0\\xf4\\xd9\\xa7\\x92m\\x84\\xe5\\xab\\x9c\\x84\\x96k\\xc2+Y\\x0f\\x9ci#p\\xd6z\\xd6\\x81\\xe9\\xb2D\\x99h\\'z\\x0b\\xd0\\xe4W\\x8a|C\\xea\\xf3\\x94\\xb8}\\x87t\\x13\\xf5u\\xbd\\xcb\\x89\\t\\xb6\\xa1a\\x8a\\x9cC\\r\\xab\\xd3\\xa1\\xdf\\xffW\\xe0LY\\x18\\x83\\x05*\\x85\\xa9u\\xf4\\xb4\\xe4\\xfc\\xda\\xb4JB~\\xdeTd\\x07\\xcc\\xed\\x1a\\x80\\x08`\\xb1\\xefB\\xf9j:\\x85\\xbc\\xb0\\x94\\x8dbR\\xe8\\n>w8\\xf6\\x11F'"
395 | ]
396 | },
397 | {
398 | "cell_type": "markdown",
399 | "metadata": {},
400 | "source": [
401 | "3. Work in pairs. One plays as Alice, one as Bob.\n",
402 | "Alice generates a keypair and sends her public key to Bob. Bob encrypts a message and sends it to Alice.\n",
403 | "Alice decrypts the message."
404 | ]
405 | },
406 | {
407 | "cell_type": "markdown",
408 | "metadata": {},
409 | "source": [
410 | "4. Work in pairs. One plays as Alice, one as Bob. Bob generates a keypair and sends his public key to Alice.\n",
411 | "Alice generates a random key and sends it to Bob using RSA. Then Alice encrypts a message using AES-CTR and sends it to Bob.\n",
412 | "Bob decrypts the message."
413 | ]
414 | },
415 | {
416 | "cell_type": "code",
417 | "execution_count": null,
418 | "metadata": {},
419 | "outputs": [],
420 | "source": []
421 | }
422 | ],
423 | "metadata": {
424 | "kernelspec": {
425 | "display_name": "Python 3 (ipykernel)",
426 | "language": "python",
427 | "name": "python3"
428 | },
429 | "language_info": {
430 | "codemirror_mode": {
431 | "name": "ipython",
432 | "version": 3
433 | },
434 | "file_extension": ".py",
435 | "mimetype": "text/x-python",
436 | "name": "python",
437 | "nbconvert_exporter": "python",
438 | "pygments_lexer": "ipython3",
439 | "version": "3.9.12"
440 | }
441 | },
442 | "nbformat": 4,
443 | "nbformat_minor": 2
444 | }
445 |
--------------------------------------------------------------------------------
/Secret Sharing (gf).ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Secret Sharing"
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "# Uncomment and execute the last line\n",
17 | "# if the pycryptodomex package is missing \n",
18 | "# !pip install pycryptodomex"
19 | ]
20 | },
21 | {
22 | "cell_type": "code",
23 | "execution_count": null,
24 | "metadata": {},
25 | "outputs": [],
26 | "source": [
27 | "from binascii import hexlify, unhexlify\n",
28 | "from Cryptodome.Random import get_random_bytes\n",
29 | "from Cryptodome.Protocol.SecretSharing import Shamir"
30 | ]
31 | },
32 | {
33 | "cell_type": "markdown",
34 | "metadata": {},
35 | "source": [
36 | "The Shamir scheme can be implemented over the Galois Field $GF(2^{128})$"
37 | ]
38 | },
39 | {
40 | "cell_type": "code",
41 | "execution_count": null,
42 | "metadata": {},
43 | "outputs": [],
44 | "source": [
45 | "# Generate a random secret\n",
46 | "secret = get_random_bytes(16)\n",
47 | "hexlify(secret)"
48 | ]
49 | },
50 | {
51 | "cell_type": "code",
52 | "execution_count": null,
53 | "metadata": {},
54 | "outputs": [],
55 | "source": [
56 | "# Now split the shares\n",
57 | "t = 2\n",
58 | "w = 5\n",
59 | "shares = Shamir.split(t, w, secret)"
60 | ]
61 | },
62 | {
63 | "cell_type": "code",
64 | "execution_count": null,
65 | "metadata": {
66 | "scrolled": true
67 | },
68 | "outputs": [],
69 | "source": [
70 | "# Now print the shares\n",
71 | "for idx, share in shares:\n",
72 | " print(\"x = %d, y = %s\" % (idx, hexlify(share)) )"
73 | ]
74 | },
75 | {
76 | "cell_type": "code",
77 | "execution_count": null,
78 | "metadata": {},
79 | "outputs": [],
80 | "source": [
81 | "# Pick two shares (e.g. 2 and 4)\n",
82 | "available = [ shares[1], shares[3] ]\n",
83 | "hexlify( Shamir.combine(available) )"
84 | ]
85 | },
86 | {
87 | "cell_type": "code",
88 | "execution_count": null,
89 | "metadata": {},
90 | "outputs": [],
91 | "source": [
92 | "# if we use only one share\n",
93 | "available = [ shares[1] ]\n",
94 | "hexlify( Shamir.combine(available) )"
95 | ]
96 | },
97 | {
98 | "cell_type": "markdown",
99 | "metadata": {},
100 | "source": [
101 | "# Lab work\n",
102 | "\n",
103 | "We have the following shares with $t = 2$.\n",
104 | "Are there any wrong shares? Which ones?"
105 | ]
106 | },
107 | {
108 | "cell_type": "code",
109 | "execution_count": null,
110 | "metadata": {},
111 | "outputs": [],
112 | "source": [
113 | "hexshares = [(1, b'ce9e5ad55b4c7d13389238afee6d1911'),\n",
114 | " (2, b'0563b1a58880f544769690f3d6ab1757'),\n",
115 | " (3, b'43c8e88a39c48d76b36af7383ee91295'),\n",
116 | " (4, b'929867442f19efeaea9fc14ba7270b5c'),\n",
117 | " (5, b'd4333e6b9e5d9dd82f63a7804f650e9e')]"
118 | ]
119 | },
120 | {
121 | "cell_type": "code",
122 | "execution_count": null,
123 | "metadata": {},
124 | "outputs": [],
125 | "source": [
126 | "shares = [(x,unhexlify(y)) for x,y in hexshares]"
127 | ]
128 | },
129 | {
130 | "cell_type": "code",
131 | "execution_count": null,
132 | "metadata": {},
133 | "outputs": [],
134 | "source": [
135 | "hexlify( Shamir.combine( (shares[0],shares[1]) ) )"
136 | ]
137 | },
138 | {
139 | "cell_type": "code",
140 | "execution_count": null,
141 | "metadata": {},
142 | "outputs": [],
143 | "source": [
144 | "hexlify( Shamir.combine( (shares[0],shares[2]) ) )"
145 | ]
146 | },
147 | {
148 | "cell_type": "code",
149 | "execution_count": null,
150 | "metadata": {},
151 | "outputs": [],
152 | "source": [
153 | "hexlify( Shamir.combine( (shares[0],shares[3]) ) )"
154 | ]
155 | },
156 | {
157 | "cell_type": "code",
158 | "execution_count": null,
159 | "metadata": {},
160 | "outputs": [],
161 | "source": [
162 | "hexlify( Shamir.combine( (shares[0],shares[4]) ) )"
163 | ]
164 | },
165 | {
166 | "cell_type": "code",
167 | "execution_count": null,
168 | "metadata": {},
169 | "outputs": [],
170 | "source": []
171 | }
172 | ],
173 | "metadata": {
174 | "kernelspec": {
175 | "display_name": "Python 3 (ipykernel)",
176 | "language": "python",
177 | "name": "python3"
178 | },
179 | "language_info": {
180 | "codemirror_mode": {
181 | "name": "ipython",
182 | "version": 3
183 | },
184 | "file_extension": ".py",
185 | "mimetype": "text/x-python",
186 | "name": "python",
187 | "nbconvert_exporter": "python",
188 | "pygments_lexer": "ipython3",
189 | "version": "3.9.7"
190 | }
191 | },
192 | "nbformat": 4,
193 | "nbformat_minor": 2
194 | }
195 |
--------------------------------------------------------------------------------
/Secret Sharing.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Secret Sharing"
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "from sympy.matrices import Matrix"
17 | ]
18 | },
19 | {
20 | "cell_type": "markdown",
21 | "metadata": {},
22 | "source": [
23 | "Suppose we want to share the secret $m=5$ to five players so that three of them must cooperate.\n",
24 | "We create the random polynomial\n",
25 | "\n",
26 | "$ s(x) = 5 + 7x +3x^2 \\mod 13 $\n"
27 | ]
28 | },
29 | {
30 | "cell_type": "code",
31 | "execution_count": null,
32 | "metadata": {},
33 | "outputs": [],
34 | "source": [
35 | "p = 13\n",
36 | "s = lambda x: (5 + 7*x + 3*x*x) % p"
37 | ]
38 | },
39 | {
40 | "cell_type": "markdown",
41 | "metadata": {},
42 | "source": [
43 | "We distribute the shares to players 1, 2, 3, 4, and 5"
44 | ]
45 | },
46 | {
47 | "cell_type": "code",
48 | "execution_count": null,
49 | "metadata": {},
50 | "outputs": [],
51 | "source": [
52 | "# the share with index 0 is the secret\n",
53 | "# Do not share it!\n",
54 | "s(0)"
55 | ]
56 | },
57 | {
58 | "cell_type": "code",
59 | "execution_count": null,
60 | "metadata": {},
61 | "outputs": [],
62 | "source": [
63 | "share = [(i,s(i)) for i in range(1,6)]\n",
64 | "share"
65 | ]
66 | },
67 | {
68 | "cell_type": "markdown",
69 | "metadata": {},
70 | "source": [
71 | "We pick three shares and rebuild the secret.\n",
72 | "We use (2,5), (3,1), and (5,11)"
73 | ]
74 | },
75 | {
76 | "cell_type": "code",
77 | "execution_count": null,
78 | "metadata": {},
79 | "outputs": [],
80 | "source": [
81 | "M = Matrix( \n",
82 | " [ \n",
83 | " [ 1, 2, pow(2,2,p) ], \n",
84 | " [ 1, 3, pow(3,2,p) ], \n",
85 | " [ 1, 5, pow(5,2,p) ] \n",
86 | " ] \n",
87 | ")\n",
88 | "M"
89 | ]
90 | },
91 | {
92 | "cell_type": "code",
93 | "execution_count": null,
94 | "metadata": {},
95 | "outputs": [],
96 | "source": [
97 | "V = Matrix([5, 1, 11])\n",
98 | "V"
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": null,
104 | "metadata": {},
105 | "outputs": [],
106 | "source": [
107 | "# We need the inverse of M modulo p\n",
108 | "Mi = M.inv_mod(p)\n",
109 | "Mi"
110 | ]
111 | },
112 | {
113 | "cell_type": "code",
114 | "execution_count": null,
115 | "metadata": {},
116 | "outputs": [],
117 | "source": [
118 | "# The result is the vector of coefficients of s\n",
119 | "# The first value is the secret\n",
120 | "Mi * V %p"
121 | ]
122 | },
123 | {
124 | "cell_type": "markdown",
125 | "metadata": {},
126 | "source": [
127 | "## Lab Work\n",
128 | "Let's test the homomorphic properties of Shamir's scheme. Work in groups of four: a Dealer, two Players (Alice and Bob) and an Observer (Charlie).\n",
129 | "\n",
130 | "1. Use the parameter $p=97$.\n",
131 | "2. The Dealer chooses two secrets: $m$ and $n$.\n",
132 | "3. The Dealer generates a first-degree random polynomial to share secret $m$.\n",
133 | "4. The Dealer gives share (1,ym1) to Alice and share (2,ym2) to Bob.\n",
134 | "5. The Dealer generates a new first-degree random polynomial to share secret $n$. Remember to use fresh random coefficients.\n",
135 | "6. The Dealer gives share (1,yn1) to Alice and share (2,yn2) to Bob.\n",
136 | "7. Alice computes the new share (1,ym1 + yn1 mod p) and gives it to Charlie\n",
137 | "8. Bob computes the new share (2,ym2 + yn2 mod p) and gives it to Charlie\n",
138 | "9. Charlie recovers the secret $z$ from the two shares. The correct result is $z=m+n \\mod p$."
139 | ]
140 | },
141 | {
142 | "cell_type": "markdown",
143 | "metadata": {},
144 | "source": [
145 | "# Challenge"
146 | ]
147 | },
148 | {
149 | "cell_type": "markdown",
150 | "metadata": {},
151 | "source": [
152 | "We provide 5 shares of a secret with threshold $t=3$. One of them is wrong.\n",
153 | "Your goal is to find the secret."
154 | ]
155 | },
156 | {
157 | "cell_type": "code",
158 | "execution_count": 1,
159 | "metadata": {},
160 | "outputs": [],
161 | "source": [
162 | "#Public prime number\n",
163 | "p = 23"
164 | ]
165 | },
166 | {
167 | "cell_type": "code",
168 | "execution_count": 2,
169 | "metadata": {},
170 | "outputs": [],
171 | "source": [
172 | "shares = [(1, 19), (2, 17), (3, 4), (4, 9), (5, 14)]"
173 | ]
174 | },
175 | {
176 | "cell_type": "code",
177 | "execution_count": null,
178 | "metadata": {},
179 | "outputs": [],
180 | "source": []
181 | }
182 | ],
183 | "metadata": {
184 | "kernelspec": {
185 | "display_name": "Python 3 (ipykernel)",
186 | "language": "python",
187 | "name": "python3"
188 | },
189 | "language_info": {
190 | "codemirror_mode": {
191 | "name": "ipython",
192 | "version": 3
193 | },
194 | "file_extension": ".py",
195 | "mimetype": "text/x-python",
196 | "name": "python",
197 | "nbconvert_exporter": "python",
198 | "pygments_lexer": "ipython3",
199 | "version": "3.11.7"
200 | }
201 | },
202 | "nbformat": 4,
203 | "nbformat_minor": 4
204 | }
205 |
--------------------------------------------------------------------------------
/StreamCiphers.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "id": "eb51cc5f-e9f7-40c9-9151-684b416713af",
7 | "metadata": {},
8 | "outputs": [],
9 | "source": [
10 | "%pip install -q cryptography mediapy\n",
11 | "\n",
12 | "# Some imports\n",
13 | "from os import urandom\n",
14 | "import struct\n",
15 | "from binascii import hexlify\n",
16 | "import numpy as np\n",
17 | "import mediapy as media\n",
18 | "\n",
19 | "from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\n",
20 | "# from cryptography.hazmat.backends import default_backend"
21 | ]
22 | },
23 | {
24 | "cell_type": "markdown",
25 | "id": "7c9079ed-6e89-4bc7-9a87-87d3224d19c7",
26 | "metadata": {},
27 | "source": [
28 | "# Using ChaCha20"
29 | ]
30 | },
31 | {
32 | "cell_type": "code",
33 | "execution_count": null,
34 | "id": "266ae1b8-6fca-4f55-a738-1964e7404997",
35 | "metadata": {},
36 | "outputs": [],
37 | "source": [
38 | "# key is 256 bits (32 bytes)\n",
39 | "key = urandom(32)\n",
40 | "\n",
41 | "# nonce is a random value (64 bits) concatenated to a counter (64 bits)\n",
42 | "# note that IETF standard has a different split (96/32) \n",
43 | "nonce = urandom(8)\n",
44 | "counter = 0\n",
45 | "full_nonce = struct.pack(\" \"ECB cannot be used because you can see the penguin\""
200 | ]
201 | },
202 | {
203 | "cell_type": "code",
204 | "execution_count": null,
205 | "metadata": {},
206 | "outputs": [],
207 | "source": [
208 | "# Load the penguin image\n",
209 | "# Uncomment the following line if you get an error about a missing file\n",
210 | "#!wget -q https://raw.githubusercontent.com/gverticale/network-security-and-cryptography/master/tux_gray.png\n",
211 | "tux_png = media.read_image('https://raw.githubusercontent.com/gverticale/network-security-and-cryptography/master/tux_gray.png')\n",
212 | "\n",
213 | "media.show_image(tux_png,height=480, title='Tux')"
214 | ]
215 | },
216 | {
217 | "cell_type": "code",
218 | "execution_count": null,
219 | "metadata": {},
220 | "outputs": [],
221 | "source": [
222 | "# Keep only luminance and serialize the image\n",
223 | "# The plaintext is a string of bytes\n",
224 | "tux = tux_png[:,:,1] * 255\n",
225 | "tux = tux.astype(np.uint8)\n",
226 | "p = tux.tobytes()"
227 | ]
228 | },
229 | {
230 | "cell_type": "code",
231 | "execution_count": null,
232 | "metadata": {},
233 | "outputs": [],
234 | "source": [
235 | "# Generate a key and an instance of AES\n",
236 | "k = urandom(KEYLEN)\n",
237 | "cipher = Cipher(algorithms.AES(k), modes.ECB())"
238 | ]
239 | },
240 | {
241 | "cell_type": "code",
242 | "execution_count": null,
243 | "metadata": {},
244 | "outputs": [],
245 | "source": [
246 | "# Encrypt the image\n",
247 | "aes_encrypt = cipher.encryptor()\n",
248 | "c = aes_encrypt.update(p) + aes_encrypt.finalize()"
249 | ]
250 | },
251 | {
252 | "cell_type": "code",
253 | "execution_count": null,
254 | "metadata": {},
255 | "outputs": [],
256 | "source": [
257 | "# Reshape the ciphertext into a matrix of bytes \n",
258 | "# Show the ciphertext\n",
259 | "encrypted_tux = np.frombuffer(c, dtype = np.uint8).reshape(tux.shape)\n",
260 | "\n",
261 | "media.show_image(encrypted_tux,height=480, title='Encrypted Tux')"
262 | ]
263 | },
264 | {
265 | "cell_type": "markdown",
266 | "metadata": {},
267 | "source": [
268 | "## Example 4\n",
269 | "We encrypt the Linux mascot with deterministic CTR, and see that patterns disappear."
270 | ]
271 | },
272 | {
273 | "cell_type": "code",
274 | "execution_count": null,
275 | "metadata": {},
276 | "outputs": [],
277 | "source": [
278 | "# Generate a key and an instance of AES\n",
279 | "k = urandom(KEYLEN)"
280 | ]
281 | },
282 | {
283 | "cell_type": "code",
284 | "execution_count": null,
285 | "metadata": {},
286 | "outputs": [],
287 | "source": [
288 | "# Generate the starting counter (in deterministic CTR, we start from 0)\n",
289 | "iv = b'\\x00'*BLOCKLEN"
290 | ]
291 | },
292 | {
293 | "cell_type": "code",
294 | "execution_count": null,
295 | "metadata": {},
296 | "outputs": [],
297 | "source": [
298 | "# Generate an instance of AES with the given key and nonce\n",
299 | "cipher = Cipher(algorithms.AES(k), modes.CTR(iv))"
300 | ]
301 | },
302 | {
303 | "cell_type": "code",
304 | "execution_count": null,
305 | "metadata": {},
306 | "outputs": [],
307 | "source": [
308 | "# Encrypt the image\n",
309 | "aes_encrypt = cipher.encryptor()\n",
310 | "c = aes_encrypt.update(p) + aes_encrypt.finalize()"
311 | ]
312 | },
313 | {
314 | "cell_type": "code",
315 | "execution_count": null,
316 | "metadata": {},
317 | "outputs": [],
318 | "source": [
319 | "# Reshape the ciphertext into a matrix of bytes \n",
320 | "# Show the ciphertext\n",
321 | "encrypted_tux = np.frombuffer(c, dtype = np.uint8).reshape(tux.shape)\n",
322 | "\n",
323 | "media.show_image(encrypted_tux,height=480, title='Encrypted Tux')"
324 | ]
325 | },
326 | {
327 | "cell_type": "markdown",
328 | "metadata": {},
329 | "source": [
330 | "## Example 5\n",
331 | "We generate a new ciphertext with the same key and still use deterministic CTR.\n",
332 | "We then see that we can then learn about the plaintext "
333 | ]
334 | },
335 | {
336 | "cell_type": "code",
337 | "execution_count": null,
338 | "metadata": {},
339 | "outputs": [],
340 | "source": [
341 | "# Load \"The Black Cat\" by Edgar Allan Poe \n",
342 | "# Uncomment the following line if you get an error about a missing file\n",
343 | "# !wget -q https://raw.githubusercontent.com/gverticale/network-security-and-cryptography/master/cat.txt\n",
344 | "\n",
345 | "catfile = requests.get('https://raw.githubusercontent.com/gverticale/network-security-and-cryptography/master/cat.txt')\n",
346 | "cat = catfile.content\n",
347 | "\n",
348 | "#with open('cat.txt', 'rb') as myfile:\n",
349 | "# cat=myfile.read()\n",
350 | "\n",
351 | "# The file is shorter than the image, so we make it the same size\n",
352 | "plaintext_cat = 50 * cat\n",
353 | "plaintext_cat = plaintext_cat[0:len(p)]"
354 | ]
355 | },
356 | {
357 | "cell_type": "code",
358 | "execution_count": null,
359 | "metadata": {},
360 | "outputs": [],
361 | "source": [
362 | "# Encrypt the text with the same key and IV\n",
363 | "cipher = Cipher(algorithms.AES(k), modes.CTR(iv))\n",
364 | "aes_encrypt = cipher.encryptor()\n",
365 | "encrypted_cat = aes_encrypt.update(plaintext_cat) + aes_encrypt.finalize()"
366 | ]
367 | },
368 | {
369 | "cell_type": "code",
370 | "execution_count": null,
371 | "metadata": {},
372 | "outputs": [],
373 | "source": [
374 | "# Reshape the encrypted poem into a matrix\n",
375 | "encrypted_cat_rect = np.frombuffer(encrypted_cat, dtype = np.uint8).reshape(tux.shape)"
376 | ]
377 | },
378 | {
379 | "cell_type": "code",
380 | "execution_count": null,
381 | "metadata": {},
382 | "outputs": [],
383 | "source": [
384 | "# Calculate the XOR between the ciphertexts\n",
385 | "ciphertext_xor = np.bitwise_xor(encrypted_cat_rect, encrypted_tux)\n",
386 | "\n",
387 | "media.show_image(ciphertext_xor,height=480, title='Xored Tux')"
388 | ]
389 | },
390 | {
391 | "cell_type": "markdown",
392 | "metadata": {},
393 | "source": [
394 | "# Example 6"
395 | ]
396 | },
397 | {
398 | "cell_type": "markdown",
399 | "metadata": {},
400 | "source": [
401 | "Let's use an authenticated cipher: AES-GCM"
402 | ]
403 | },
404 | {
405 | "cell_type": "code",
406 | "execution_count": null,
407 | "metadata": {},
408 | "outputs": [],
409 | "source": [
410 | "# Generate a key and an instance of AES-GCM\n",
411 | "# The standard requires an 96-bit random IV\n",
412 | "k = urandom(KEYLEN)\n",
413 | "iv = urandom(12)\n",
414 | "cipher = Cipher(algorithms.AES(k), modes.GCM(iv))"
415 | ]
416 | },
417 | {
418 | "cell_type": "code",
419 | "execution_count": null,
420 | "metadata": {},
421 | "outputs": [],
422 | "source": [
423 | "# Encrypt \"The Black Cat\" and authenticate the string \"A poem\"\n",
424 | "gcm_encrypt = cipher.encryptor()\n",
425 | "gcm_encrypt.authenticate_additional_data(b\"A poem\")\n",
426 | "encrypted_cat = gcm_encrypt.update(plaintext_cat) + gcm_encrypt.finalize()\n",
427 | "tag = gcm_encrypt.tag"
428 | ]
429 | },
430 | {
431 | "cell_type": "code",
432 | "execution_count": null,
433 | "metadata": {},
434 | "outputs": [],
435 | "source": [
436 | "# Now decrypt\n",
437 | "cipher = Cipher(algorithms.AES(k), modes.GCM(iv,tag))"
438 | ]
439 | },
440 | {
441 | "cell_type": "code",
442 | "execution_count": null,
443 | "metadata": {},
444 | "outputs": [],
445 | "source": [
446 | "gcm_decrypt = cipher.decryptor()\n",
447 | "gcm_decrypt.authenticate_additional_data(b\"A new poem\")\n",
448 | "try:\n",
449 | " decrypted_cat = gcm_decrypt.update(encrypted_cat) + gcm_decrypt.finalize()\n",
450 | " print(decrypted_cat)\n",
451 | "except InvalidTag:\n",
452 | " print(\"Not authentic\")"
453 | ]
454 | },
455 | {
456 | "cell_type": "markdown",
457 | "metadata": {},
458 | "source": [
459 | "# Lab Activity: randomized CTR"
460 | ]
461 | },
462 | {
463 | "cell_type": "markdown",
464 | "metadata": {},
465 | "source": [
466 | "1. Encrypt tux with randomized CTR\n",
467 | "2. Encrypt cat with randomized CTR\n",
468 | "3. Compute the bitwise xor of the ciphertexts\n",
469 | "4. Show the result"
470 | ]
471 | },
472 | {
473 | "cell_type": "markdown",
474 | "metadata": {},
475 | "source": [
476 | "# Lab Activity: Malleability of AES-CTR"
477 | ]
478 | },
479 | {
480 | "cell_type": "markdown",
481 | "metadata": {},
482 | "source": [
483 | "1. Start from \"THE BLACK CAT\"\n",
484 | "2. Encrypt it using AES-CTR (use a random IV)\n",
485 | "3. Using ciphertext malleability change the ciphertext so that the title of the poem becomes \"THE GREEN CAT\"\n",
486 | "4. Decrypt it showing the modified text\n",
487 | "5. Repeat using AES-GCM and verify that it fails"
488 | ]
489 | },
490 | {
491 | "cell_type": "markdown",
492 | "metadata": {},
493 | "source": [
494 | "_Quick note on the python library: the output of the encryption is immutable, you need to convert it to a list to modify it (command `list`) , then you need to convert it back to a bytes object (command `bytes`)_"
495 | ]
496 | },
497 | {
498 | "cell_type": "code",
499 | "execution_count": null,
500 | "metadata": {},
501 | "outputs": [],
502 | "source": []
503 | }
504 | ],
505 | "metadata": {
506 | "kernelspec": {
507 | "display_name": "Python 3 (ipykernel)",
508 | "language": "python",
509 | "name": "python3"
510 | },
511 | "language_info": {
512 | "codemirror_mode": {
513 | "name": "ipython",
514 | "version": 3
515 | },
516 | "file_extension": ".py",
517 | "mimetype": "text/x-python",
518 | "name": "python",
519 | "nbconvert_exporter": "python",
520 | "pygments_lexer": "ipython3",
521 | "version": "3.11.7"
522 | }
523 | },
524 | "nbformat": 4,
525 | "nbformat_minor": 4
526 | }
527 |
--------------------------------------------------------------------------------
/cat.txt:
--------------------------------------------------------------------------------
1 | THE BLACK CAT
2 |
3 | by Edgar Allan Poe
4 | (1843)
5 |
6 | FOR the most wild, yet most homely narrative which I am about to pen, I
7 | neither expect nor solicit belief. Mad indeed would I be to expect it, in a
8 | case where my very senses reject their own evidence. Yet, mad am I not --and
9 | very surely do I not dream. But to-morrow I die, and to-day I would
10 | unburthen my soul. My immediate purpose is to place before the world,
11 | plainly, succinctly, and without comment, a series of mere household events.
12 | In their consequences, these events have terrified --have tortured --have
13 | destroyed me. Yet I will not attempt to expound them. To me, they have
14 | presented little but Horror --to many they will seem less terrible than
15 | baroques. Hereafter, perhaps, some intellect may be found which will reduce
16 | my phantasm to the common-place --some intellect more calm, more logical,
17 | and far less excitable than my own, which will perceive, in the
18 | circumstances I detail with awe, nothing more than an ordinary succession of
19 | very natural causes and effects.
20 | From my infancy I was noted for the docility and humanity of my
21 | disposition. My tenderness of heart was even so conspicuous as to make me
22 | the jest of my companions. I was especially fond of animals, and was
23 | indulged by my parents with a great variety of pets. With these I spent most
24 | of my time, and never was so happy as when feeding and caressing them. This
25 | peculiar of character grew with my growth, and in my manhood, I derived from
26 | it one of my principal sources of pleasure. To those who have cherished an
27 | affection for a faithful and sagacious dog, I need hardly be at the trouble
28 | of explaining the nature or the intensity of the gratification thus
29 | derivable. There is something in the unselfish and self-sacrificing love of
30 | a brute, which goes directly to the heart of him who has had frequent
31 | occasion to test the paltry friendship and gossamer fidelity of mere Man.
32 | I married early, and was happy to find in my wife a disposition not
33 | uncongenial with my own. Observing my partiality for domestic pets, she lost
34 | no opportunity of procuring those of the most agreeable kind. We had birds,
35 | gold fish, a fine dog, rabbits, a small monkey, and a cat.
36 | This latter was a remarkably large and beautiful animal, entirely black,
37 | and sagacious to an astonishing degree. In speaking of his intelligence, my
38 | wife, who at heart was not a little tinctured with superstition, made
39 | frequent allusion to the ancient popular notion, which regarded all black
40 | cats as witches in disguise. Not that she was ever serious upon this point
41 | --and I mention the matter at all for no better reason than that it happens,
42 | just now, to be remembered.
43 | Pluto --this was the cat's name --was my favorite pet and playmate. I
44 | alone fed him, and he attended me wherever I went about the house. It was
45 | even with difficulty that I could prevent him from following me through the
46 | streets.
47 | Our friendship lasted, in this manner, for several years, during which my
48 | general temperament and character --through the instrumentality of the Fiend
49 | Intemperance --had (I blush to confess it) experienced a radical alteration
50 | for the worse. I grew, day by day, more moody, more irritable, more
51 | regardless of the feelings of others. I suffered myself to use intemperate
52 | language to my At length, I even offered her personal violence. My pets, of
53 | course, were made to feel the change in my disposition. I not only
54 | neglected, but ill-used them. For Pluto, however, I still retained
55 | sufficient regard to restrain me from maltreating him, as I made no scruple
56 | of maltreating the rabbits, the monkey, or even the dog, when by accident,
57 | or through affection, they came in my way. But my disease grew upon me --for
58 | what disease is like Alcohol! --and at length even Pluto, who was now
59 | becoming old, and consequently somewhat peevish --even Pluto began to
60 | experience the effects of my ill temper.
61 | One night, returning home, much intoxicated, from one of my haunts about
62 | town, I fancied that the cat avoided my presence. I seized him; when, in his
63 | fright at my violence, he inflicted a slight wound upon my hand with his
64 | teeth. The fury of a demon instantly possessed me. I knew myself no longer.
65 | My original soul seemed, at once, to take its flight from my body; and a
66 | more than fiendish malevolence, gin-nurtured, thrilled every fibre of my
67 | frame. I took from my waistcoat-pocket a pen-knife, opened it, grasped the
68 | poor beast by the throat, and deliberately cut one of its eyes from the
69 | socket! I blush, I burn, I shudder, while I pen the damnable atrocity.
70 | When reason returned with the morning --when I had slept off the fumes of
71 | the night's debauch --I experienced a sentiment half of horror, half of
72 | remorse, for the crime of which I had been guilty; but it was, at best, a
73 | feeble and equivocal feeling, and the soul remained untouched. I again
74 | plunged into excess, and soon drowned in wine all memory of the deed.
75 | In the meantime the cat slowly recovered. The socket of the lost eye
76 | presented, it is true, a frightful appearance, but he no longer appeared to
77 | suffer any pain. He went about the house as usual, but, as might be
78 | expected, fled in extreme terror at my approach. I had so much of my old
79 | heart left, as to be at first grieved by this evident dislike on the part of
80 | a creature which had once so loved me. But this feeling soon gave place to
81 | irritation. And then came, as if to my final and irrevocable overthrow, the
82 | spirit of PERVERSENESS. Of this spirit philosophy takes no account. Yet I am
83 | not more sure that my soul lives, than I am that perverseness is one of the
84 | primitive impulses of the human heart --one of the indivisible primary
85 | faculties, or sentiments, which give direction to the character of Man. Who
86 | has not, a hundred times, found himself committing a vile or a silly action,
87 | for no other reason than because he knows he should not? Have we not a
88 | perpetual inclination, in the teeth of our best judgment, to violate that
89 | which is Law, merely because we understand it to be such? This spirit of
90 | perverseness, I say, came to my final overthrow. It was this unfathomable
91 | longing of the soul to vex itself --to offer violence to its own nature --to
92 | do wrong for the wrong's sake only --that urged me to continue and finally
93 | to consummate the injury I had inflicted upon the unoffending brute. One
94 | morning, in cool blood, I slipped a noose about its neck and hung it to the
95 | limb of a tree; --hung it with the tears streaming from my eyes, and with
96 | the bitterest remorse at my heart; --hung it because I knew that it had
97 | loved me, and because I felt it had given me no reason of offence; --hung it
98 | because I knew that in so doing I was committing a sin --a deadly sin that
99 | would so jeopardize my immortal soul as to place it --if such a thing were
100 | possible --even beyond the reach of the infinite mercy of the Most Merciful
101 | and Most Terrible God.
102 | On the night of the day on which this cruel deed was done, I was aroused
103 | from sleep by the cry of fire. The curtains of my bed were in flames. The
104 | whole house was blazing. It was with great difficulty that my wife, a
105 | servant, and myself, made our escape from the conflagration. The destruction
106 | was complete. My entire worldly wealth was swallowed up, and I resigned
107 | myself thenceforward to despair.
108 | I am above the weakness of seeking to establish a sequence of cause and
109 | effect, between the disaster and the atrocity. But I am detailing a chain of
110 | facts --and wish not to leave even a possible link imperfect. On the day
111 | succeeding the fire, I visited the ruins. The walls, with one exception, had
112 | fallen in. This exception was found in a compartment wall, not very thick,
113 | which stood about the middle of the house, and against which had rested the
114 | head of my bed. The plastering had here, in great measure, resisted the
115 | action of the fire --a fact which I attributed to its having been recently
116 | spread. About this wall a dense crowd were collected, and many persons
117 | seemed to be examining a particular portion of it with every minute and
118 | eager attention. The words "strange!" "singular!" and other similar
119 | expressions, excited my curiosity. I approached and saw, as if graven in bas
120 | relief upon the white surface, the figure of a gigantic cat. The impression
121 | was given with an accuracy truly marvellous. There was a rope about the
122 | animal's neck.
123 | When I first beheld this apparition --for I could scarcely regard it as
124 | less --my wonder and my terror were extreme. But at length reflection came
125 | to my aid. The cat, I remembered, had been hung in a garden adjacent to the
126 | house. Upon the alarm of fire, this garden had been immediately filled by
127 | the crowd --by some one of whom the animal must have been cut from the tree
128 | and thrown, through an open window, into my chamber. This had probably been
129 | done with the view of arousing me from sleep. The falling of other walls had
130 | compressed the victim of my cruelty into the substance of the freshly-spread
131 | plaster; the lime of which, had then with the flames, and the ammonia from
132 | the carcass, accomplished the portraiture as I saw it.
133 | Although I thus readily accounted to my reason, if not altogether to my
134 | conscience, for the startling fact 'just detailed, it did not the less fall
135 | to make a deep impression upon my fancy. For months I could not rid myself
136 | of the phantasm of the cat; and, during this period, there came back into my
137 | spirit a half-sentiment that seemed, but was not, remorse. I went so far as
138 | to regret the loss of the animal, and to look about me, among the vile
139 | haunts which I now habitually frequented, for another pet of the same
140 | species, and of somewhat similar appearance, with which to supply its place.
141 |
142 | One night as I sat, half stupefied, in a den of more than infamy, my
143 | attention was suddenly drawn to some black object, reposing upon the head of
144 | one of the immense hogsheads of Gin, or of Rum, which constituted the chief
145 | furniture of the apartment. I had been looking steadily at the top of this
146 | hogshead for some minutes, and what now caused me surprise was the fact that
147 | I had not sooner perceived the object thereupon. I approached it, and
148 | touched it with my hand. It was a black cat --a very large one --fully as
149 | large as Pluto, and closely resembling him in every respect but one. Pluto
150 | had not a white hair upon any portion of his body; but this cat had a large,
151 | although indefinite splotch of white, covering nearly the whole region of
152 | the breast.
153 | Upon my touching him, he immediately arose, purred loudly, rubbed against
154 | my hand, and appeared delighted with my notice. This, then, was the very
155 | creature of which I was in search. I at once offered to purchase it of the
156 | landlord; but this person made no claim to it --knew nothing of it --had
157 | never seen it before.
158 | I continued my caresses, and, when I prepared to go home, the animal
159 | evinced a disposition to accompany me. I permitted it to do so; occasionally
160 | stooping and patting it as I proceeded. When it reached the house it
161 | domesticated itself at once, and became immediately a great favorite with my
162 | wife.
163 | For my own part, I soon found a dislike to it arising within me. This was
164 | just the reverse of what I had anticipated; but I know not how or why it was
165 | --its evident fondness for myself rather disgusted and annoyed. By slow
166 | degrees, these feelings of disgust and annoyance rose into the bitterness of
167 | hatred. I avoided the creature; a certain sense of shame, and the
168 | remembrance of my former deed of cruelty, preventing me from physically
169 | abusing it. I did not, for some weeks, strike, or otherwise violently ill
170 | use it; but gradually --very gradually --I came to look upon it with
171 | unutterable loathing, and to flee silently from its odious presence, as from
172 | the breath of a pestilence.
173 | What added, no doubt, to my hatred of the beast, was the discovery, on
174 | the morning after I brought it home, that, like Pluto, it also had been
175 | deprived of one of its eyes. This circumstance, however, only endeared it to
176 | my wife, who, as I have already said, possessed, in a high degree, that
177 | humanity of feeling which had once been my distinguishing trait, and the
178 | source of many of my simplest and purest pleasures.
179 | With my aversion to this cat, however, its partiality for myself seemed
180 | to increase. It followed my footsteps with a pertinacity which it would be
181 | difficult to make the reader comprehend. Whenever I sat, it would crouch
182 | beneath my chair, or spring upon my knees, covering me with its loathsome
183 | caresses. If I arose to walk it would get between my feet and thus nearly
184 | throw me down, or, fastening its long and sharp claws in my dress, clamber,
185 | in this manner, to my breast. At such times, although I longed to destroy it
186 | with a blow, I was yet withheld from so doing, partly it at by a memory of
187 | my former crime, but chiefly --let me confess it at once --by absolute dread
188 | of the beast.
189 | This dread was not exactly a dread of physical evil-and yet I should be
190 | at a loss how otherwise to define it. I am almost ashamed to own --yes, even
191 | in this felon's cell, I am almost ashamed to own --that the terror and
192 | horror with which the animal inspired me, had been heightened by one of the
193 | merest chimaeras it would be possible to conceive. My wife had called my
194 | attention, more than once, to the character of the mark of white hair, of
195 | which I have spoken, and which constituted the sole visible difference
196 | between the strange beast and the one I had y si destroyed. The reader will
197 | remember that this mark, although large, had been originally very
198 | indefinite; but, by slow degrees --degrees nearly imperceptible, and which
199 | for a long time my Reason struggled to reject as fanciful --it had, at
200 | length, assumed a rigorous distinctness of outline. It was now the
201 | representation of an object that I shudder to name --and for this, above
202 | all, I loathed, and dreaded, and would have rid myself of the monster had I
203 | dared --it was now, I say, the image of a hideous --of a ghastly thing --of
204 | the GALLOWS! --oh, mournful and terrible engine of Horror and of Crime --of
205 | Agony and of Death!
206 | And now was I indeed wretched beyond the wretchedness of mere Humanity.
207 | And a brute beast --whose fellow I had contemptuously destroyed --a brute
208 | beast to work out for me --for me a man, fashioned in the image of the High
209 | God --so much of insufferable wo! Alas! neither by day nor by night knew I
210 | the blessing of Rest any more! During the former the creature left me no
211 | moment alone; and, in the latter, I started, hourly, from dreams of
212 | unutterable fear, to find the hot breath of the thing upon my face, and its
213 | vast weight --an incarnate Night-Mare that I had no power to shake off
214 | --incumbent eternally upon my heart!
215 | Beneath the pressure of torments such as these, the feeble remnant of the
216 | good within me succumbed. Evil thoughts became my sole intimates --the
217 | darkest and most evil of thoughts. The moodiness of my usual temper
218 | increased to hatred of all things and of all mankind; while, from the
219 | sudden, frequent, and ungovernable outbursts of a fury to which I now
220 | blindly abandoned myself, my uncomplaining wife, alas! was the most usual
221 | and the most patient of sufferers.
222 | One day she accompanied me, upon some household errand, into the cellar
223 | of the old building which our poverty compelled us to inhabit. The cat
224 | followed me down the steep stairs, and, nearly throwing me headlong,
225 | exasperated me to madness. Uplifting an axe, and forgetting, in my wrath,
226 | the childish dread which had hitherto stayed my hand, I aimed a blow at the
227 | animal which, of course, would have proved instantly fatal had it descended
228 | as I wished. But this blow was arrested by the hand of my wife. Goaded, by
229 | the interference, into a rage more than demoniacal, I withdrew my arm from
230 | her grasp and buried the axe in her brain. She fell dead upon the spot,
231 | without a groan.
232 | This hideous murder accomplished, I set myself forthwith, and with entire
233 | deliberation, to the task of concealing the body. I knew that I could not
234 | remove it from the house, either by day or by night, without the risk of
235 | being observed by the neighbors. Many projects entered my mind. At one
236 | period I thought of cutting the corpse into minute fragments, and destroying
237 | them by fire. At another, I resolved to dig a grave for it in the floor of
238 | the cellar. Again, I deliberated about casting it in the well in the yard
239 | --about packing it in a box, as if merchandize, with the usual arrangements,
240 | and so getting a porter to take it from the house. Finally I hit upon what I
241 | considered a far better expedient than either of these. I determined to wall
242 | it up in the cellar --as the monks of the middle ages are recorded to have
243 | walled up their victims.
244 | For a purpose such as this the cellar was well adapted. Its walls were
245 | loosely constructed, and had lately been plastered throughout with a rough
246 | plaster, which the dampness of the atmosphere had prevented from hardening.
247 | Moreover, in one of the walls was a projection, caused by a false chimney,
248 | or fireplace, that had been filled up, and made to resemble the rest of the
249 | cellar. I made no doubt that I could readily displace the at this point,
250 | insert the corpse, and wall the whole up as before, so that no eye could
251 | detect anything suspicious.
252 | And in this calculation I was not deceived. By means of a crow-bar I
253 | easily dislodged the bricks, and, having carefully deposited the body
254 | against the inner wall, I propped it in that position, while, with little
255 | trouble, I re-laid the whole structure as it originally stood. Having
256 | procured mortar, sand, and hair, with every possible precaution, I prepared
257 | a plaster could not every poss be distinguished from the old, and with this
258 | I very carefully went over the new brick-work. When I had finished, I felt
259 | satisfied that all was right. The wall did not present the slightest
260 | appearance of having been disturbed. The rubbish on the floor was picked up
261 | with the minutest care. I looked around triumphantly, and said to myself
262 | --"Here at least, then, my labor has not been in vain."
263 | My next step was to look for the beast which had been the cause of so
264 | much wretchedness; for I had, at length, firmly resolved to put it to death.
265 | Had I been able to meet with it, at the moment, there could have been no
266 | doubt of its fate; but it appeared that the crafty animal had been alarmed
267 | at the violence of my previous anger, and forebore to present itself in my
268 | present mood. It is impossible to describe, or to imagine, the deep, the
269 | blissful sense of relief which the absence of the detested creature
270 | occasioned in my bosom. It did not make its appearance during the night
271 | --and thus for one night at least, since its introduction into the house, I
272 | soundly and tranquilly slept; aye, slept even with the burden of murder upon
273 | my soul!
274 | The second and the third day passed, and still my tormentor came not.
275 | Once again I breathed as a free-man. The monster, in terror, had fled the
276 | premises forever! I should behold it no more! My happiness was supreme! The
277 | guilt of my dark deed disturbed me but little. Some few inquiries had been
278 | made, but these had been readily answered. Even a search had been instituted
279 | --but of course nothing was to be discovered. I looked upon my future
280 | felicity as secured.
281 | Upon the fourth day of the assassination, a party of the police came,
282 | very unexpectedly, into the house, and proceeded again to make rigorous
283 | investigation of the premises. Secure, however, in the inscrutability of my
284 | place of concealment, I felt no embarrassment whatever. The officers bade me
285 | accompany them in their search. They left no nook or corner unexplored. At
286 | length, for the third or fourth time, they descended into the cellar. I
287 | quivered not in a muscle. My heart beat calmly as that of one who slumbers
288 | in innocence. I walked the cellar from end to end. I folded my arms upon my
289 | bosom, and roamed easily to and fro. The police were thoroughly satisfied
290 | and prepared to depart. The glee at my heart was too strong to be
291 | restrained. I burned to say if but one word, by way of triumph, and to
292 | render doubly sure their assurance of my guiltlessness.
293 | "Gentlemen," I said at last, as the party ascended the steps, "I delight
294 | to have allayed your suspicions. I wish you all health, and a little more
295 | courtesy. By the bye, gentlemen, this --this is a very well constructed
296 | house." (In the rabid desire to say something easily, I scarcely knew what I
297 | uttered at all.) --"I may say an excellently well constructed house. These
298 | walls --are you going, gentlemen? --these walls are solidly put together";
299 | and here, through the mere phrenzy of bravado, I rapped heavily, with a cane
300 | which I held in my hand, upon that very portion of the brick-work behind
301 | which stood the corpse of the wife of my bosom.
302 | But may God shield and deliver me from the fangs of the Arch-Fiend! No
303 | sooner had the reverberation of my blows sunk into silence than I was
304 | answered by a voice from within the tomb! --by a cry, at first muffled and
305 | broken, like the sobbing of a child, and then quickly swelling into one
306 | long, loud, and continuous scream, utterly anomalous and inhuman --a howl
307 | --a wailing shriek, half of horror and half of triumph, such as might have
308 | arisen only out of hell, conjointly from the throats of the damned in their
309 | agony and of the demons that exult in the damnation.
310 | Of my own thoughts it is folly to speak. Swooning, I staggered to the
311 | opposite wall. For one instant the party upon the stairs remained
312 | motionless, through extremity of terror and of awe. In the next, a dozen
313 | stout arms were tolling at the wall. It fell bodily. The corpse, already
314 | greatly decayed and clotted with gore, stood erect before the eyes of the
315 | spectators. Upon its head, with red extended mouth and solitary eye of fire,
316 | sat the hideous beast whose craft had seduced me into murder, and whose
317 | informing voice had consigned me to the hangman. I had walled the monster up
318 | within the tomb!
--------------------------------------------------------------------------------
/encrypted_cat.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gverticale/network-security-and-cryptography/abe1e414a0f587528aa51059f1f61d56aae3555b/encrypted_cat.txt
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | matplotlib
2 | sympy
3 | pycryptodomex
--------------------------------------------------------------------------------
/tux.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gverticale/network-security-and-cryptography/abe1e414a0f587528aa51059f1f61d56aae3555b/tux.png
--------------------------------------------------------------------------------
/tux_gray.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gverticale/network-security-and-cryptography/abe1e414a0f587528aa51059f1f61d56aae3555b/tux_gray.png
--------------------------------------------------------------------------------