├── .DS_Store ├── .ipynb_checkpoints ├── My First Python3 Notebook-checkpoint.ipynb ├── P3wNT Notebook 1-checkpoint.ipynb ├── P3wNT Notebook 2-checkpoint.ipynb ├── P3wNT Notebook 3-checkpoint.ipynb ├── P3wNT Notebook 4-checkpoint.ipynb ├── P3wNT Notebook 5-checkpoint.ipynb ├── P3wNT Notebook 6-checkpoint.ipynb └── P3wNT Notebook 7-checkpoint.ipynb ├── LICENSE ├── My First Python Notebook.ipynb ├── My First Python3 Notebook.ipynb ├── P3wNT Notebook 1.ipynb ├── P3wNT Notebook 2.ipynb ├── P3wNT Notebook 3.ipynb ├── P3wNT Notebook 4.ipynb ├── P3wNT Notebook 5.ipynb ├── P3wNT Notebook 6.ipynb ├── P3wNT Notebook 7.ipynb ├── PwNT Notebook 1.ipynb ├── PwNT Notebook 2.ipynb ├── PwNT Notebook 3.ipynb ├── PwNT Notebook 4.ipynb ├── PwNT Notebook 5.ipynb ├── PwNT Notebook 6.ipynb ├── PwNT Notebook 7.ipynb └── README.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MartyWeissman/Python-for-number-theory/5e819522e52e6a75c5dec597f024729bfc9ba4c5/.DS_Store -------------------------------------------------------------------------------- /.ipynb_checkpoints/My First Python3 Notebook-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# A brief introduction to Jupyter Notebooks for Python 3." 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "This is a Jupyter notebook. **Python** is a programming language, and a **Jupyter notebook** is an interactive document which contains text (like what you're reading now) and Python code. Jupyter notebooks will be used throughout the tutorial, and this is a brief introduction to the interface.\n", 15 | "\n", 16 | "## Table of Contents\n", 17 | "\n", 18 | "1. [Notebook cells](#cells)\n", 19 | "2. [Markdown syntax](#markdown)\n", 20 | "3. [Saving, loading, printing](#files)" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "" 28 | ] 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "metadata": {}, 33 | "source": [ 34 | "## Notebook cells" 35 | ] 36 | }, 37 | { 38 | "cell_type": "markdown", 39 | "metadata": {}, 40 | "source": [ 41 | "Click inside the cell below, in the box to the right of the `In []:` prompt. A border should appear around the cell, with a green bar at the left, indicating that it's active. Then press *shift-Enter* (hold down the shift key while pressing the Enter key) on the keyboard to **evaluate** the cell. " 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "2+2" 51 | ] 52 | }, 53 | { 54 | "cell_type": "markdown", 55 | "metadata": {}, 56 | "source": [ 57 | "If an output message like `Out[1]: 4` appeared, then everything is working correctly!" 58 | ] 59 | }, 60 | { 61 | "cell_type": "markdown", 62 | "metadata": {}, 63 | "source": [ 64 | "Jupyter notebooks are built out of **cells**. There are two primary types of cells: **Markdown cells** and **Code cells**. Textual content will be contained in Markdown cells like this one. Programming content will be contained in Code cells, like the `2+2` cell above.\n", 65 | "\n", 66 | "If a cell has a green border, that means that you're currently editing it. If it has a blue border, that means that the cell is selected (and can be cut and pasted, etc.) but not in edit-mode. Otherwise it is not active.\n", 67 | "\n", 68 | "To edit a Code cell, click anywhere within its evaluation box. For example, you can click inside the `2+2` cell, change the numbers to `2+3` and re-evaluate with *shift-Enter*. \n", 69 | "\n", 70 | "To edit a Markdown cell like this one, double-click anywhere within its body. You can write Markdown just like any text document, for the most part. When you're done editing a Markdown cell, press *shift-Enter*.\n", 71 | "\n", 72 | "To change a selected cell from Code to Markdown or back again, you should see a dropdown menu with \"Markdown\" or \"Code\" visible, just above your notebook interface. Just drop down to select the type of the cell. For practice, select the cell below to a Markdown cell, and write a sentence or two. Complete it with a *shift-Enter*." 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": null, 78 | "metadata": {}, 79 | "outputs": [], 80 | "source": [ 81 | "# Change this cell to a Markdown cell, and write something." 82 | ] 83 | }, 84 | { 85 | "cell_type": "markdown", 86 | "metadata": {}, 87 | "source": [ 88 | "Now, change the cell below to a Code cell, and use it to compute `999 * 999`." 89 | ] 90 | }, 91 | { 92 | "cell_type": "markdown", 93 | "metadata": {}, 94 | "source": [ 95 | "(I'm a markdown cell. Change me to a Code cell and compute `999*999`)" 96 | ] 97 | }, 98 | { 99 | "cell_type": "markdown", 100 | "metadata": {}, 101 | "source": [ 102 | "Often you'll want to **insert a new cell** above or below a given cell. To do this, you need to select the cell in one of the following ways. Select a Code cell with a single click **outside** of its evaluation box, e.g., click where it says `In [ ]:`. Select a Markdown cell with a single-click anywhere in its body.\n", 103 | "\n", 104 | "If you have selected the cell correctly, a blue border should be visible around it. Once the blue border is visible, you can add a new cell **above** it by pressing the **a** key on the keyboard. You can add a new cell **below** it by pressing the **b** key on the keyboard. Try to add a new cell above and below the Markdown cell below. The newly created cells are probably Code cells by default.\n", 105 | "\n", 106 | "Instead of **a** or **b**, you can also press **x**. That will delete the cell, so be careful and save often." 107 | ] 108 | }, 109 | { 110 | "cell_type": "markdown", 111 | "metadata": {}, 112 | "source": [ 113 | "(I'm a markdown cell. Add a new cell above and below me.)" 114 | ] 115 | }, 116 | { 117 | "cell_type": "markdown", 118 | "metadata": {}, 119 | "source": [ 120 | "A quick note: there are a few **invisible cells** in this notebook, and in other notebooks in the tutorial. In fact, one of these sneaky cells is just below this one! It's a Markdown cell, as you will see if you double-click it. Its content is ``, which is a snippet of HTML code. This is a little placeholder, which enables the links in the table of contents. Don't change those Markdown cells, unless you want to break the links in the table of contents." 121 | ] 122 | }, 123 | { 124 | "cell_type": "markdown", 125 | "metadata": {}, 126 | "source": [ 127 | "" 128 | ] 129 | }, 130 | { 131 | "cell_type": "markdown", 132 | "metadata": {}, 133 | "source": [ 134 | "## Basic Markdown for Jupyter notebooks" 135 | ] 136 | }, 137 | { 138 | "cell_type": "markdown", 139 | "metadata": {}, 140 | "source": [ 141 | "You will learn more about Python code in the tutorial. As you are learning, you should experiment in code cells, and write answers to questions and other notes in markdown cells. Markdown is a neat text-editing language, a sort of shorthand that extends HTML. Here is a brief guide to typing in Markdown." 142 | ] 143 | }, 144 | { 145 | "cell_type": "markdown", 146 | "metadata": {}, 147 | "source": [ 148 | "Most of the time, you can type Markdown just like any old text document. One little difference is that to start a new line, you have to insert an extra empty line in the Markdown. Double-click this cell to see how the new paragraph was started below. \n", 149 | "\n", 150 | "Markdown has many more features that you'll notice in this document: there are different typefaces, lists, headings, links, and more. " 151 | ] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "metadata": {}, 156 | "source": [ 157 | "### Typefaces\n", 158 | "\n", 159 | "To change from plain text to *italics* or to **boldface**, you surround the text by asterisks or double-asterisks. Double-click inside this Markdown cell to see how it was done! Then insert a new Markdown cell below this one to experiment. Strictly speaking, the single-asterisks are used to convert to the HTML `` tag, which places emphasis on text. The double-asterisks convert to the HTML `` tag, which is often boldfaced. But different web-browsers behave differently." 160 | ] 161 | }, 162 | { 163 | "cell_type": "markdown", 164 | "metadata": {}, 165 | "source": [ 166 | "### Lists\n", 167 | "\n", 168 | "Often it is useful to make lists. The two kinds of lists we'll use are numbered lists and unnumbered lists. These are easy in Markdown. For a numbered list, just start each new line with a number. Double-click this cell to see how it was done.\n", 169 | "\n", 170 | "1. This is the first line.\n", 171 | "2. This is the second line.\n", 172 | "3. This is the third line." 173 | ] 174 | }, 175 | { 176 | "cell_type": "markdown", 177 | "metadata": {}, 178 | "source": [ 179 | "For an unnumbered (bulleted) list, start each new line with a dash `-` (a few other symbols work too). Double-click this cell to see how it was done.\n", 180 | "\n", 181 | "- This is the first line.\n", 182 | "- This is the second line.\n", 183 | "- This is the third line.\n", 184 | "\n", 185 | "Now I'm back to ordinary text again." 186 | ] 187 | }, 188 | { 189 | "cell_type": "markdown", 190 | "metadata": {}, 191 | "source": [ 192 | "You can nest your lists. But people get too attached to nested hierarchies in their writing and presentations. Lists have their place, but paragraphs should be more common. If you must nest a list, double-click this cell to see how it was done, with a bit of indentation. \n", 193 | "\n", 194 | "- This is the first line.\n", 195 | " - This is the first subline within the first line.\n", 196 | " - This is the second subline within the first line.\n", 197 | "- This is the second line.\n", 198 | "- This is the third line.\n", 199 | "\n", 200 | "Now I'm back to ordinary text again." 201 | ] 202 | }, 203 | { 204 | "cell_type": "markdown", 205 | "metadata": {}, 206 | "source": [ 207 | "### Headings\n", 208 | "\n", 209 | "There are different levels of headings, i.e., headings, subheadings, etc., which typically render as boldface text of different sizes. To make a top-level heading, a single hashtag `#` is used. The next level heading is created with a double hashtag `##`, and so on. Double-click this cell to see how it was done.\n", 210 | "\n", 211 | "# A top-level heading.\n", 212 | "## The next-level heading.\n", 213 | "### A third-level heading.\n", 214 | "#### A fourth-level heading. " 215 | ] 216 | }, 217 | { 218 | "cell_type": "markdown", 219 | "metadata": {}, 220 | "source": [ 221 | "### Links\n", 222 | "\n", 223 | "Finally, we discuss how to insert web-links in your Markdown code. For example, here is a [link to the webpage to buy An Illustrated Theory of Numbers](http://bookstore.ams.org/mbk-105). The general syntax is that the displayed text goes in brackets followed by the URL (web address) in parentheses. Double-click this cell to see how it was done." 224 | ] 225 | }, 226 | { 227 | "cell_type": "markdown", 228 | "metadata": {}, 229 | "source": [ 230 | "### Conclusion\n", 231 | "\n", 232 | "There is much much more you can do with Markdown. In fact, Markdown is a superset of HTML, so you can put just about any basic web content in a Markdown cell. A quick google search will turn up lots of Markdown guides, and it's best to search for Markdown and Jupyter to find a guide for Jupyter's particular flavor of Markdown (which differs a bit from WordPress markdown, for example). " 233 | ] 234 | }, 235 | { 236 | "cell_type": "markdown", 237 | "metadata": { 238 | "collapsed": true 239 | }, 240 | "source": [ 241 | "" 242 | ] 243 | }, 244 | { 245 | "cell_type": "markdown", 246 | "metadata": {}, 247 | "source": [ 248 | "## Saving, loading, and printing notebooks" 249 | ] 250 | }, 251 | { 252 | "cell_type": "markdown", 253 | "metadata": {}, 254 | "source": [ 255 | "You can save, load, and print Jupyter notebooks. In fact, it's probably a good time to save this notebook since you've edited the markdown so far. Go to \"File...Save and Checkpoint\" (the File menu just under \"Jupyter\") to save your notebook so far.\n", 256 | "\n" 257 | ] 258 | }, 259 | { 260 | "cell_type": "markdown", 261 | "metadata": {}, 262 | "source": [ 263 | "The standard notebook file format is `.ipynb` which stands for \"iPython Notebook\", since Jupyter used to be called iPython. If you go to \"File...Download as...\", then \"IPython Notebook\" will be the top choice. You will always be able to reload your notebook and edit it, if you save it as an iPython Notebook.\n", 264 | "\n", 265 | "You may also want to save a copy as an `.html` file. HTML is the code used to render webpages, and so it's good for sharing with anyone with a web browser. Also, your web browser can probably print the HTML file nicely, so it's a good format for printing. You can go directly to \"File...Print preview\" to see what the notebook will look like when printed.\n", 266 | "\n", 267 | "To open a Python notebook, you can go to \"File...Open\" or you can return to your original Jupyter tab (if it's still there) and browse directories to find notebook files. But Jupyter must be started to load python notebooks on your computer.\n", 268 | "\n", 269 | "\n", 270 | "\n" 271 | ] 272 | }, 273 | { 274 | "cell_type": "markdown", 275 | "metadata": {}, 276 | "source": [ 277 | "One more tool to learn about is [GitHub](https://github.com/). GitHub is a website which allows users to share and develop software of all sorts. It's used for collaborative software development, and has many desirable features like \"versioning\" (keeping track of versions along the way as various parties make edits). You can freely use GitHub to store your Python notebooks. GitHub takes a bit of practice, but it's worth the effort in the long run. \n", 278 | "\n", 279 | "The tutorial notebooks are stored on GitHub for a few reasons. First, they can be easily edited and improved. Second, they become freely and publicly available. Go to [my GitHub page](https://github.com/MartyWeissman/Python-for-number-theory) to see them! Third, even though they are stored in `.ipynb` format, anyone can view Python notebooks on the web using the [Jupyter Notebook Viewer](https://nbviewer.jupyter.org/). For example, you can use the Jupyter Notebook Viewer to see [this notebook online](https://nbviewer.jupyter.org/github/MartyWeissman/Python-for-number-theory/blob/master/My%20First%20Python%20Notebook.ipynb)." 280 | ] 281 | }, 282 | { 283 | "cell_type": "markdown", 284 | "metadata": {}, 285 | "source": [ 286 | "Now you know more than enough to begin the Python tutorials. Download the notebooks and **happy programming**!" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": null, 292 | "metadata": {}, 293 | "outputs": [], 294 | "source": [] 295 | } 296 | ], 297 | "metadata": { 298 | "kernelspec": { 299 | "display_name": "Python 3", 300 | "language": "python", 301 | "name": "python3" 302 | }, 303 | "language_info": { 304 | "codemirror_mode": { 305 | "name": "ipython", 306 | "version": 3 307 | }, 308 | "file_extension": ".py", 309 | "mimetype": "text/x-python", 310 | "name": "python", 311 | "nbconvert_exporter": "python", 312 | "pygments_lexer": "ipython3", 313 | "version": "3.6.4" 314 | } 315 | }, 316 | "nbformat": 4, 317 | "nbformat_minor": 1 318 | } 319 | -------------------------------------------------------------------------------- /.ipynb_checkpoints/P3wNT Notebook 7-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Part 7: The RSA Cryptosystem in Python 3.x" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "In the previous notebook, we studied a few basic ciphers together with Diffie-Hellman key exchange. The Vigenère cipher we studied uses a **secret key** for encrypting and decrypting messages. The same key is used for both encryption and decryption, so we say it is a **symmetric key** cipher. In order for two parties to share the same secret key, we studied the Diffie-Hellman protocol, whose security rests on the difficulty of the discrete logarithm problem.\n", 15 | "\n", 16 | "Although this represents progress towards secure communication, it is particularly vulnerable to problems of authentication. For example, imagine a \"man-in-the-middle attack\": Alice and Bob wish to communicate securely, and begin the Diffie-Hellman protocol over an insecure line. But **Eve** has intercepted the line. To Alice, she pretends to be Bob, and to Bob, she pretends to be Alice. She goes through the Diffie-Hellman protocol with each, obtaining two secret keys, and decrypting/encrypting messages as they pass through her computer. In this way, Alice and Bob think they are talking to each other, but Eve is just passing (and understanding) their messages the whole time!\n", 17 | "\n", 18 | "To thwart such an attack, we need some type of authentication. We need something **asymmetric** -- something one person can do that no other person can do, like a verifiable signature, so that we can be sure we're communicating with the intended person. For such a purpose, we introduce the RSA cryptosystem. Computationally based on modular exponentiation, its security rests on the difficulty of factoring large numbers.\n", 19 | "\n", 20 | "The material in this notebook complements Chapter 7 of [An Illustrated Theory of Numbers](http://illustratedtheoryofnumbers.com/index.html)." 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "## Table of Contents\n", 28 | "\n", 29 | "- [Euler's theorem and modular roots](#euler)\n", 30 | "- [The RSA protocol](#RSA)" 31 | ] 32 | }, 33 | { 34 | "cell_type": "markdown", 35 | "metadata": {}, 36 | "source": [ 37 | "" 38 | ] 39 | }, 40 | { 41 | "cell_type": "markdown", 42 | "metadata": {}, 43 | "source": [ 44 | "## Euler's Theorem and Modular Roots\n", 45 | "\n", 46 | "Recall Fermat's Little Theorem: if $p$ is prime and $GCD(a,p) = 1$, then $a^{p-1} \\equiv 1$ mod $p$. This is a special case of Euler's theorem, which holds for any modulus $m$.\n", 47 | "\n", 48 | "### Euler's theorem and the totient\n", 49 | "\n", 50 | "Euler's theorem states: if $m$ is a positive integer and $GCD(a,m) = 1$, then $a^{\\phi(m)} \\equiv 1$ mod $m$. Here $\\phi(m)$ denotes the **totient** of $m$, which is the number of elements of $\\{ 1,...,m \\}$ which are coprime to $m$. We give a brute force implementation of the totient first, using our old Euclidean algorithm code for the GCD." 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": {}, 57 | "outputs": [], 58 | "source": [ 59 | "def GCD(a,b):\n", 60 | " while b: # Recall that != means \"not equal to\".\n", 61 | " a, b = b, a % b\n", 62 | " return abs(a)\n", 63 | "\n", 64 | "def totient(m):\n", 65 | " tot = 0 # The running total.\n", 66 | " j = 0\n", 67 | " while j < m: # We go up to m, because the totient of 1 is 1 by convention.\n", 68 | " j = j + 1 # Last step of while loop: j = m-1, and then j = j+1, so j = m.\n", 69 | " if GCD(j,m) == 1:\n", 70 | " tot = tot + 1\n", 71 | " return tot" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "totient(17) # The totient of a prime p should be p-1." 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "metadata": {}, 87 | "outputs": [], 88 | "source": [ 89 | "totient(1000)" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": null, 95 | "metadata": {}, 96 | "outputs": [], 97 | "source": [ 98 | "totient(1) # Check a borderline case, to make sure we didn't make an off-by-one error." 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "17**totient(1000) % 1000 # Let's demonstrate Euler's theorem. Note GCD(17,1000) = 1." 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": null, 113 | "metadata": {}, 114 | "outputs": [], 115 | "source": [ 116 | "pow(17,totient(1000),1000) # A more efficient version, using the pow command." 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": null, 122 | "metadata": {}, 123 | "outputs": [], 124 | "source": [ 125 | "%timeit totient(123456)" 126 | ] 127 | }, 128 | { 129 | "cell_type": "markdown", 130 | "metadata": {}, 131 | "source": [ 132 | "The totient is a **multiplicative function**, meaning that if $GCD(a,b) = 1$, then $\\phi(ab) = \\phi(a) \\phi(b)$. Therefore, the totient of number can be found quickly from the totient of the prime powers within its decomposition. We can re-implement the totient using our functions for prime decomposition and multiplicative functions from [Notebook 4](http://illustratedtheoryofnumbers.com/prog.html#notebooks)." 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": null, 138 | "metadata": {}, 139 | "outputs": [], 140 | "source": [ 141 | "from math import sqrt # We'll want to use the square root.\n", 142 | "\n", 143 | "def smallest_factor(n):\n", 144 | " '''\n", 145 | " Gives the smallest prime factor of n.\n", 146 | " '''\n", 147 | " if n < 2:\n", 148 | " return None # No prime factors!\n", 149 | " \n", 150 | " test_factor = 2 # The smallest possible prime factor.\n", 151 | " max_factor = sqrt(n) # we don't have to search past sqrt(n).\n", 152 | " \n", 153 | " while test_factor <= max_factor:\n", 154 | " if n%test_factor == 0:\n", 155 | " return test_factor\n", 156 | " test_factor = test_factor + 1 # This could be sped up.\n", 157 | " \n", 158 | " return n # If we didn't find a factor up to sqrt(n), n itself is prime!\n", 159 | "\n", 160 | "def decompose(N):\n", 161 | " '''\n", 162 | " Gives the unique prime decomposition of a positive integer N,\n", 163 | " as a dictionary with primes as keys and exponents as values.\n", 164 | " '''\n", 165 | " current_number = N # We'll divide out factors from current_number until we get 1.\n", 166 | " decomp = {} # An empty dictionary to start.\n", 167 | " while current_number > 1:\n", 168 | " p = smallest_factor(current_number) # The smallest prime factor of the current number.\n", 169 | " if p in decomp.keys(): # Is p already in the list of keys?\n", 170 | " decomp[p] = decomp[p] + 1 # Increase the exponent (value with key p) by 1.\n", 171 | " else: # \"else\" here means \"if p is not in decomp.keys()\".\n", 172 | " decomp[p] = 1 # Creates a new entry in the dictionary, with key p and value 1.\n", 173 | " current_number = current_number // p # Factor out p.\n", 174 | " return decomp\n", 175 | "\n", 176 | "def mult_function(f_pp):\n", 177 | " '''\n", 178 | " When a function f_pp(p,e) of two arguments is input,\n", 179 | " this outputs a multiplicative function obtained from f_pp\n", 180 | " via prime decomposition.\n", 181 | " '''\n", 182 | " def f(n):\n", 183 | " D = decompose(n)\n", 184 | " result = 1\n", 185 | " for p in D:\n", 186 | " result = result * f_pp(p, D[p])\n", 187 | " return result\n", 188 | " \n", 189 | " return f" 190 | ] 191 | }, 192 | { 193 | "cell_type": "markdown", 194 | "metadata": {}, 195 | "source": [ 196 | "When $p^e$ is a prime power, the numbers among $1, \\ldots, p^e$ are coprime to $p^e$ precisely when they are **not** multiples of $p$. Therefore, the totient of a prime power is pretty easy to compute:\n", 197 | "$$\\phi(p^e) = p^e - p^{e-1} = p^{e-1} (p-1).$$\n", 198 | "We implement this, and use the multiplicative function code to complete the implementation of the totient." 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": null, 204 | "metadata": {}, 205 | "outputs": [], 206 | "source": [ 207 | "def totient_pp(p,e):\n", 208 | " return (p**(e-1)) * (p-1)" 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "metadata": {}, 214 | "source": [ 215 | "Note that for efficiency, the computation of $p^{e-1}(p-1)$ is probably faster than the computation of $p^e - p^{e-1}$ (which relies on two exponents). But Python is very smart about these sorts of things, and might do some optimization which makes the computation faster. It should be very fast anyways, in the 10-20 nanosecond range!" 216 | ] 217 | }, 218 | { 219 | "cell_type": "code", 220 | "execution_count": null, 221 | "metadata": {}, 222 | "outputs": [], 223 | "source": [ 224 | "totient = mult_function(totient_pp)" 225 | ] 226 | }, 227 | { 228 | "cell_type": "code", 229 | "execution_count": null, 230 | "metadata": {}, 231 | "outputs": [], 232 | "source": [ 233 | "totient(1000)" 234 | ] 235 | }, 236 | { 237 | "cell_type": "code", 238 | "execution_count": null, 239 | "metadata": {}, 240 | "outputs": [], 241 | "source": [ 242 | "%timeit totient(123456)" 243 | ] 244 | }, 245 | { 246 | "cell_type": "markdown", 247 | "metadata": {}, 248 | "source": [ 249 | "This should be **much** faster than the previous brute-force computation of the totient." 250 | ] 251 | }, 252 | { 253 | "cell_type": "markdown", 254 | "metadata": {}, 255 | "source": [ 256 | "### Modular roots" 257 | ] 258 | }, 259 | { 260 | "cell_type": "markdown", 261 | "metadata": {}, 262 | "source": [ 263 | "A consequence of Euler's theorem is that -- depending on the modulus -- some exponentiation can be \"reversed\" by another exponentiation, a form of taking a \"root\" in modular arithmetic. For example, if we work modulo $100$, and $GCD(a,100) = 1$, then Euler's theorem states that\n", 264 | "$$a^{40} \\equiv 1 \\text{ mod } 100.$$\n", 265 | "It follows that $a^{80} \\equiv 1$ and $a^{81} \\equiv a$, modulo $100$. Expanding this, we find\n", 266 | "$$a \\equiv a^{81} = a^{3 \\cdot 27} = (a^3)^{27} \\text{ mod } 100.$$\n", 267 | "\n", 268 | "What all this computation shows is that \"raising to the 27th power\" is like \"taking the cube root\", modulo 100 (and with appropriate bases)." 269 | ] 270 | }, 271 | { 272 | "cell_type": "code", 273 | "execution_count": null, 274 | "metadata": {}, 275 | "outputs": [], 276 | "source": [ 277 | "for b in range(20):\n", 278 | " b_cubed = pow(b,3,100)\n", 279 | " bb = pow(b_cubed,27,100)\n", 280 | " print(b, b_cubed, bb, GCD(b,100) == 1)" 281 | ] 282 | }, 283 | { 284 | "cell_type": "markdown", 285 | "metadata": {}, 286 | "source": [ 287 | "In every line ending with `True`, the first and third numbers should match. This will happen in some `False` lines too, but not reliably since Euler's theorem does not apply there.\n", 288 | "\n", 289 | "We found the exponent 27 -- reversing the cubing operation -- by an ad hoc sort of procedure. The relationship between 27 and 3, which made things work, is that\n", 290 | "$$3 \\cdot 27 \\equiv 1 \\text{ mod } 40.$$\n", 291 | "In other words, $3 \\cdot 27 = 1 + 40k$ for some (positive, in fact) integer $k$.\n", 292 | "\n", 293 | "Recalling that $40 = \\phi(100)$, this relationship and Euler's theorem imply that\n", 294 | "$$a^{3 \\cdot 27} = a^{1 + 40k} \\equiv a^1 = a \\text{ mod } 100.$$\n", 295 | "By this argument, we have the following consequence of Euler's theorem. \n", 296 | "\n", 297 | "**Theorem: ** If $GCD(a,m) = 1$, and $ef \\equiv 1$ mod $\\phi(m)$, then\n", 298 | "$$a^{ef} \\equiv a \\text{ mod } \\phi(m).$$\n", 299 | "In this way, \"raising to the $f$ power\" is like \"taking the $e$-th root\", modulo $m$. \n", 300 | "\n", 301 | "If we are given $f$, then $e$ is a **multiplicative inverse** of $f$ modulo $\\phi(m)$. In particular, such a multiplicative inverse exists if and only if $GCD(e,\\phi(m)) = 1$. The following function computes a multiplicative inverse, by adapting the `solve_LDE` function from [Notebook 2](). After all, solving $ex \\equiv 1$ mod $m$ is equivalent to solving the linear Diophantine equation $ex + my = 1$ (and only caring about the $x$-value). \n" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": null, 307 | "metadata": {}, 308 | "outputs": [], 309 | "source": [ 310 | "def mult_inverse(a,m):\n", 311 | " '''\n", 312 | " Finds the multiplicative inverse of a, mod m.\n", 313 | " If GCD(a,m) = 1, this is returned via its natural representative.\n", 314 | " Otherwise, None is returned.\n", 315 | " ''' \n", 316 | " u = a # We use u instead of dividend.\n", 317 | " v = m # We use v instead of divisor.\n", 318 | " u_hops, u_skips = 1,0 # u is built from one hop (a) and no skips.\n", 319 | " v_hops, v_skips = 0,1 # v is built from no hops and one skip (b).\n", 320 | " while v != 0: # We could just write while v:\n", 321 | " q = u // v # q stands for quotient.\n", 322 | " r = u % v # r stands for remainder. So u = q(v) + r.\n", 323 | " \n", 324 | " r_hops = u_hops - q * v_hops # Tally hops\n", 325 | " r_skips = u_skips - q * v_skips # Tally skips\n", 326 | " \n", 327 | " u,v = v,r # The new dividend,divisor is the old divisor,remainder.\n", 328 | " u_hops, v_hops = v_hops, r_hops # The new u_hops, v_hops is the old v_hops, r_hops\n", 329 | " u_skips, v_skips = v_skips, r_skips # The new u_skips, v_skips is the old v_skips, r_skips\n", 330 | " \n", 331 | " g = u # The variable g now describes the GCD of a and b.\n", 332 | " if g == 1:\n", 333 | " return u_hops % m\n", 334 | " else: # When GCD(a,m) is not 1...\n", 335 | " return None" 336 | ] 337 | }, 338 | { 339 | "cell_type": "code", 340 | "execution_count": null, 341 | "metadata": {}, 342 | "outputs": [], 343 | "source": [ 344 | "mult_inverse(3,40) # 3 times what is congruent to 1, mod 40?" 345 | ] 346 | }, 347 | { 348 | "cell_type": "code", 349 | "execution_count": null, 350 | "metadata": {}, 351 | "outputs": [], 352 | "source": [ 353 | "mult_inverse(5,40) # None should be returned." 354 | ] 355 | }, 356 | { 357 | "cell_type": "markdown", 358 | "metadata": {}, 359 | "source": [ 360 | "Let's test this out on some bigger numbers." 361 | ] 362 | }, 363 | { 364 | "cell_type": "code", 365 | "execution_count": null, 366 | "metadata": {}, 367 | "outputs": [], 368 | "source": [ 369 | "from random import randint\n", 370 | "while True:\n", 371 | " m = randint(1000000, 9999999) # a random 7-digit number\n", 372 | " e = randint(100,999) # a random 3-digit number\n", 373 | " a = randint(10,99) # a random 2-digit number\n", 374 | " if GCD(a,m) == 1:\n", 375 | " tot = totient(m)\n", 376 | " if GCD(e,tot) == 1:\n", 377 | " f = mult_inverse(e,tot)\n", 378 | " test_number = pow(a, e*f, m)\n", 379 | " print(\"Success!\")\n", 380 | " print(\"{} ^ ({} * {}) = {}, mod {}\".format(a,e,f,test_number,m))\n", 381 | " break # Escapes the loop once an example is found!" 382 | ] 383 | }, 384 | { 385 | "cell_type": "markdown", 386 | "metadata": {}, 387 | "source": [ 388 | "### Exercises\n", 389 | "\n", 390 | "1. What is the largest integer whose totient is 100? Study this by a brute force search, i.e., looping through the integers up to 10000\n", 391 | "\n", 392 | "2. For which integers $n$ is it true that $\\phi(n) = n/2$? Study this by a brute force search in order to make a conjecture. Then prove it if you can.\n", 393 | "\n", 394 | "3. Compute the totient of the numbers from 1 to 10000, and analyze the results. The totient $\\phi(n)$ is always less than $n$ when $n > 1$, but how does the ratio $\\phi(n) / n$ behave? Create a graph. What is the average value of the ratio? \n", 395 | "\n", 396 | "4. If $a^{323} \\equiv 802931$, mod $5342481$, and $GCD(a, 5342481) = 1$, and $0 < a < 5342481$, then what is $a$? \n", 397 | "\n", 398 | "5. Challenge: Create a function `superpow(x,y,z,m)` which computes $x^{y^z}$ modulo $m$ efficiently, when $GCD(x,m) = 1$ and $m$ is small enough to factor." 399 | ] 400 | }, 401 | { 402 | "cell_type": "markdown", 403 | "metadata": {}, 404 | "source": [ 405 | "" 406 | ] 407 | }, 408 | { 409 | "cell_type": "markdown", 410 | "metadata": {}, 411 | "source": [ 412 | "## The RSA protocol" 413 | ] 414 | }, 415 | { 416 | "cell_type": "markdown", 417 | "metadata": {}, 418 | "source": [ 419 | "Like Diffie-Hellman, the RSA protocol involves a series of computations in modular arithmetic, taking care to keep some numbers private while making others public. RSA was published two years after Diffie-Hellman, in 1978 by Rivest, Shamir, and Adelman (hence its name). The great advance of the RSA protocol was its **asymmetry**. While Diffie-Hellman is used for symmetric key cryptography (using the same key to encrypt and decrypt), the RSA protocol has two keys: a **public key** that can be used by anyone for encryption and a **private key** that can be used by its owner for decryption. \n", 420 | "\n", 421 | "In this way, if Alice publishes her public key online, anyone can send her an encrypted message. But as long as she keeps her private key private, **only** Alice can decrypt the messages sent to her. Such an asymmetry allows RSA to be used for authentication -- if the owner of a private key has an ability nobody else has, then this ability can be used to prove the owner's identity. In practice, this is one of the most common applications of RSA, guaranteeing that we are communicating with the intended person." 422 | ] 423 | }, 424 | { 425 | "cell_type": "markdown", 426 | "metadata": {}, 427 | "source": [ 428 | "In the RSA protocol, the **private key** is a pair of large (e.g. 512 bit) prime numbers, called $p$ and $q$. The **public key** is the pair $(N, e)$, where $N$ is defined to be the product $N = pq$ and $e$ is an auxiliary number called the exponent. The number $e$ is often (for computational efficiency and other reasons) taken to be 65537 -- the same number $e$ can be used over and over by different people. But it is absolutely crucial that the same private keys $p$ and $q$ are not used by different individuals. Individuals must create and safely keep their own private key." 429 | ] 430 | }, 431 | { 432 | "cell_type": "markdown", 433 | "metadata": {}, 434 | "source": [ 435 | "We begin with the creation of a private key $(p,q)$. We use the `SystemRandom` function (see the previous Python Notebook) to cook up cryptographically secure random numbers, and the Miller-Rabin test to certify primality." 436 | ] 437 | }, 438 | { 439 | "cell_type": "code", 440 | "execution_count": null, 441 | "metadata": {}, 442 | "outputs": [], 443 | "source": [ 444 | "from random import SystemRandom, randint\n", 445 | "\n", 446 | "def Miller_Rabin(p, base):\n", 447 | " '''\n", 448 | " Tests whether p is prime, using the given base.\n", 449 | " The result False implies that p is definitely not prime.\n", 450 | " The result True implies that p **might** be prime.\n", 451 | " It is not a perfect test!\n", 452 | " '''\n", 453 | " result = 1\n", 454 | " exponent = p-1\n", 455 | " modulus = p\n", 456 | " bitstring = bin(exponent)[2:] # Chop off the '0b' part of the binary expansion of exponent\n", 457 | " for bit in bitstring: # Iterates through the \"letters\" of the string. Here the letters are '0' or '1'.\n", 458 | " sq_result = result*result % modulus # We need to compute this in any case.\n", 459 | " if sq_result == 1:\n", 460 | " if (result != 1) and (result != exponent): # Note that exponent is congruent to -1, mod p.\n", 461 | " return False # a ROO violation occurred, so p is not prime\n", 462 | " if bit == '0':\n", 463 | " result = sq_result \n", 464 | " if bit == '1':\n", 465 | " result = (sq_result * base) % modulus\n", 466 | " if result != 1:\n", 467 | " return False # a FLT violation occurred, so p is not prime.\n", 468 | " \n", 469 | " return True # If we made it this far, no violation occurred and p might be prime.\n", 470 | "\n", 471 | "def is_prime(p, witnesses=50): # witnesses is a parameter with a default value.\n", 472 | " '''\n", 473 | " Tests whether a positive integer p is prime.\n", 474 | " For p < 2^64, the test is deterministic, using known good witnesses.\n", 475 | " Good witnesses come from a table at Wikipedia's article on the Miller-Rabin test,\n", 476 | " based on research by Pomerance, Selfridge and Wagstaff, Jaeschke, Jiang and Deng.\n", 477 | " For larger p, a number (by default, 50) of witnesses are chosen at random.\n", 478 | " '''\n", 479 | " if (p%2 == 0): # Might as well take care of even numbers at the outset!\n", 480 | " if p == 2:\n", 481 | " return True\n", 482 | " else:\n", 483 | " return False \n", 484 | " \n", 485 | " if p > 2**64: # We use the probabilistic test for large p.\n", 486 | " trial = 0\n", 487 | " while trial < witnesses:\n", 488 | " trial = trial + 1\n", 489 | " witness = randint(2,p-2) # A good range for possible witnesses\n", 490 | " if Miller_Rabin(p,witness) == False:\n", 491 | " return False\n", 492 | " return True\n", 493 | " \n", 494 | " else: # We use a determinisic test for p <= 2**64.\n", 495 | " verdict = Miller_Rabin(p,2)\n", 496 | " if p < 2047:\n", 497 | " return verdict # The witness 2 suffices.\n", 498 | " verdict = verdict and Miller_Rabin(p,3)\n", 499 | " if p < 1373653:\n", 500 | " return verdict # The witnesses 2 and 3 suffice.\n", 501 | " verdict = verdict and Miller_Rabin(p,5)\n", 502 | " if p < 25326001:\n", 503 | " return verdict # The witnesses 2,3,5 suffice.\n", 504 | " verdict = verdict and Miller_Rabin(p,7)\n", 505 | " if p < 3215031751:\n", 506 | " return verdict # The witnesses 2,3,5,7 suffice.\n", 507 | " verdict = verdict and Miller_Rabin(p,11)\n", 508 | " if p < 2152302898747:\n", 509 | " return verdict # The witnesses 2,3,5,7,11 suffice.\n", 510 | " verdict = verdict and Miller_Rabin(p,13)\n", 511 | " if p < 3474749660383:\n", 512 | " return verdict # The witnesses 2,3,5,7,11,13 suffice.\n", 513 | " verdict = verdict and Miller_Rabin(p,17)\n", 514 | " if p < 341550071728321:\n", 515 | " return verdict # The witnesses 2,3,5,7,11,17 suffice.\n", 516 | " verdict = verdict and Miller_Rabin(p,19) and Miller_Rabin(p,23)\n", 517 | " if p < 3825123056546413051:\n", 518 | " return verdict # The witnesses 2,3,5,7,11,17,19,23 suffice.\n", 519 | " verdict = verdict and Miller_Rabin(p,29) and Miller_Rabin(p,31) and Miller_Rabin(p,37)\n", 520 | " return verdict # The witnesses 2,3,5,7,11,17,19,23,29,31,37 suffice for testing up to 2^64. \n", 521 | " \n", 522 | "\n", 523 | "def random_prime(bitlength):\n", 524 | " while True:\n", 525 | " p = SystemRandom().getrandbits(bitlength) # A cryptographically secure random number.\n", 526 | " if is_prime(p):\n", 527 | " return p" 528 | ] 529 | }, 530 | { 531 | "cell_type": "code", 532 | "execution_count": null, 533 | "metadata": {}, 534 | "outputs": [], 535 | "source": [ 536 | "random_prime(100) # A random 100-bit prime" 537 | ] 538 | }, 539 | { 540 | "cell_type": "code", 541 | "execution_count": null, 542 | "metadata": {}, 543 | "outputs": [], 544 | "source": [ 545 | "random_prime(512) # A random 512-bit prime. Should be quick, thanks to Miller-Rabin!" 546 | ] 547 | }, 548 | { 549 | "cell_type": "code", 550 | "execution_count": null, 551 | "metadata": {}, 552 | "outputs": [], 553 | "source": [ 554 | "%timeit random_prime(1024) # Even 1024-bit primes should be quick!" 555 | ] 556 | }, 557 | { 558 | "cell_type": "code", 559 | "execution_count": null, 560 | "metadata": {}, 561 | "outputs": [], 562 | "source": [ 563 | "def RSA_privatekey(bitlength):\n", 564 | " '''\n", 565 | " Create private key for RSA, with given bitlength.\n", 566 | " Just a pair of big primes!\n", 567 | " '''\n", 568 | " p = random_prime(bitlength)\n", 569 | " q = random_prime(bitlength)\n", 570 | " return p,q # Returns both values, as a \"tuple\"" 571 | ] 572 | }, 573 | { 574 | "cell_type": "code", 575 | "execution_count": null, 576 | "metadata": {}, 577 | "outputs": [], 578 | "source": [ 579 | "type(RSA_privatekey(8)) # When a function returns multiple values, the type is \"tuple\"." 580 | ] 581 | }, 582 | { 583 | "cell_type": "code", 584 | "execution_count": null, 585 | "metadata": {}, 586 | "outputs": [], 587 | "source": [ 588 | "p,q = RSA_privatekey(512) # If a function outputs two values, you can assign them to two variables.\n", 589 | "print(\"Private key p = {}\".format(p))\n", 590 | "print(\"Private key q = {}\".format(q))" 591 | ] 592 | }, 593 | { 594 | "cell_type": "code", 595 | "execution_count": null, 596 | "metadata": {}, 597 | "outputs": [], 598 | "source": [ 599 | "def RSA_publickey(p,q, e = 65537):\n", 600 | " '''\n", 601 | " Makes the RSA public key out of \n", 602 | " two prime numbers p,q (the private key), \n", 603 | " and an auxiliary exponent e. \n", 604 | " By default, e = 65537.\n", 605 | " '''\n", 606 | " N = p*q\n", 607 | " return N,e" 608 | ] 609 | }, 610 | { 611 | "cell_type": "code", 612 | "execution_count": null, 613 | "metadata": {}, 614 | "outputs": [], 615 | "source": [ 616 | "N,e = RSA_publickey(p,q) # No value of e is input, so it will default to 65537\n", 617 | "\n", 618 | "print(\"Public key N = {}\".format(N)) # A big number!\n", 619 | "print(\"Public key e = {}\".format(e))" 620 | ] 621 | }, 622 | { 623 | "cell_type": "markdown", 624 | "metadata": {}, 625 | "source": [ 626 | "### Encryption and decryption\n", 627 | "\n", 628 | "Now we explain how the public key $(N,e)$ and the private key $(p,q)$ are used to encrypt and decrypt a (numerical) message $m$. If you wish to encrypt/decrypt a text message, one case use a numerical scheme like ASCII, of course. The message should be significantly shorter than the modulus, $m < N$ (ideally, shorter than the private key primes), but big enough so that $m^e$ is much bigger than $N$ (not usually a problem if $e = 65537$). \n", 629 | "\n", 630 | "The encryption procedure is simple -- it requires just one line of Python code, using the message and public key. The ciphertext $c$ is given by the formula\n", 631 | "$$c = m^e \\text{ mod } N,$$\n", 632 | "where here we mean the \"natural representative\" of $m^e$ modulo $N$. " 633 | ] 634 | }, 635 | { 636 | "cell_type": "code", 637 | "execution_count": null, 638 | "metadata": {}, 639 | "outputs": [], 640 | "source": [ 641 | "def RSA_encrypt(message, N, e):\n", 642 | " '''\n", 643 | " Encrypts message, using the public keys N,e.\n", 644 | " '''\n", 645 | " return pow(message, e, N)" 646 | ] 647 | }, 648 | { 649 | "cell_type": "code", 650 | "execution_count": null, 651 | "metadata": {}, 652 | "outputs": [], 653 | "source": [ 654 | "c = RSA_encrypt(17,N,e) # c is the ciphertext.\n", 655 | "print(\"The ciphertext is {}\".format(c)) # A very long number!" 656 | ] 657 | }, 658 | { 659 | "cell_type": "markdown", 660 | "metadata": {}, 661 | "source": [ 662 | "To decrypt the ciphertext, we need to \"undo\" the operation of raising to the $e$-th power modulo $N$. We must, effectively, take the $e$-th root of the ciphertext, modulo $N$. This is what we studied earlier in this notebook. Namely, if $c \\equiv m^e \\text{ mod } N$ is the ciphertext, and $ef \\equiv 1$ modulo $\\phi(N)$, then\n", 663 | "$$c^f \\equiv m^{ef} \\equiv m \\text{ mod } N.$$\n", 664 | "\n", 665 | "So we must raise the ciphertext to the $f$ power, where $f$ is the multiplicative inverse of $e$ modulo $\\phi(N)$. Given a giant number $N$, it is difficult to compute the totient $\\phi(N)$. But, with the **private key** $p$ and $q$ (primes), the fact that $N = pq$ implies\n", 666 | "$$\\phi(N) = (p-1) \\cdot (q-1) = pq - p - q + 1 = N - p - q + 1.$$\n", 667 | "\n", 668 | "Armed with the private key (and the public key, which everyone has), we can decrypt a message in just a few lines of Python code." 669 | ] 670 | }, 671 | { 672 | "cell_type": "code", 673 | "execution_count": null, 674 | "metadata": {}, 675 | "outputs": [], 676 | "source": [ 677 | "def RSA_decrypt(ciphertext, p,q,N,e):\n", 678 | " '''\n", 679 | " Decrypts message, using the private key (p,q) \n", 680 | " and the public key (N,e). We allow the public key N as\n", 681 | " an input parameter, to avoid recomputing it.\n", 682 | " '''\n", 683 | " tot = N - (p+q) + 1\n", 684 | " f = mult_inverse(e,tot) # This uses the Euclidean algorithm... very quick!\n", 685 | " return pow(ciphertext,f,N)" 686 | ] 687 | }, 688 | { 689 | "cell_type": "code", 690 | "execution_count": null, 691 | "metadata": {}, 692 | "outputs": [], 693 | "source": [ 694 | "RSA_decrypt(c,p,q,N,e) # We decrypt the ciphertext... what is the result?" 695 | ] 696 | }, 697 | { 698 | "cell_type": "markdown", 699 | "metadata": {}, 700 | "source": [ 701 | "That's the entire process of encryption and decryption. Encryption requires just the public key $(N,e)$ and decryption requires the private key $(p,q)$ too. Everything else is modular arithmetic, using Euler's theorem and the Euclidean algorithm to find modular multiplicative inverses.\n", 702 | "\n", 703 | "From a practical standpoint, there are many challenges, and we just mention a few here.\n", 704 | "\n", 705 | "**Key generation:** The person who constructs the private key $(p,q)$ needs to be careful. The primes $p$ and $q$ need to be pretty large (512 bits, or 1024 bits perhaps), which is not so difficult. They also need to be constructed **randomly**. For imagine that Alice comes up with her private key $(p,q)$ and Anne comes up with her private key $(q,r)$, with the same prime $q$ in common. Their public keys will include the numbers $N = pq$ and $M = qr$. If someone like Arjen comes along and starts taking GCDs of all the public keys in a database, that person will stumble upon the fact that $GCD(N,M) = q$, from which the private keys $(p,q)$ and $(q,r)$ can be derived. And this sort of disaster has happened! Poorly generated keys were stored in a database, and [discovered by Arjen Lenstra et al.](https://eprint.iacr.org/2012/064.pdf).\n", 706 | "\n", 707 | "**Security by difficulty of factoring:** The security of RSA is based on the difficulty of obtaining the private key $(p,q)$ from the public key $(N,e)$. Since $N = pq$, this is precisely the difficulty of factoring a large number $N$ into two primes (given the knowledge that it is the product of two primes). Currently it seems very difficult to factor large numbers. The RSA factoring challenges give monetary rewards for factoring such large $N$. The record (2017) is factoring a [768-bit (232 digit) number, RSA-768](https://en.wikipedia.org/wiki/RSA_numbers#RSA-768). For this reason, we may consider a 1024-bit number secure for now (i.e. $p$ and $q$ are 512-bit primes), or use a 2048-bit number if we are paranoid. If quantum computers develop sufficiently, they could make factoring large numbers easy, and RSA will have to be replaced by a quantum-secure protocol. \n", 708 | "\n", 709 | "**Web of Trust:** Trust needs to begin somewhere. Every time Alice and Bob communicate, Alice should not come up with a new private key, and give Bob the new public key. For if they are far apart, how does Bob know he's receiving Alice's public key and not talking to an eavesdropper Eve? Instead, it is better for Alice to register (in person, perhaps) her public key at some time. She can create her private key $(p,q)$ and register the resulting public key $(N,e)$ with some \"key authority\" who checks her identity at the time. The key authority then stores everyone's public keys -- effectively they say \"if you want to send a secure message to Alice, use the following public key: (..., ...)\" Then Bob can consult the key authority when he wishes to communicate securely to Alice, and this private/public key combination can be used for years.\n", 710 | "\n", 711 | "But, as one might guess, this kicks the trust question to another layer. How does Bob know he's communicating with the key authority? The key authorities need to have their own authentication mechanism, etc.. One way to avoid going down a rabbithole of mistrust is to *distribute* trust across a network of persons. Instead of a centralized \"key authority\", one can distribute one's public keys across an entire network of communicators (read about [openPGP](https://en.wikipedia.org/wiki/Pretty_Good_Privacy#OpenPGP)). Then Bob, if he wishes, can double-check Alice's public keys against the records of numerous members of the network -- assuming that hackers haven't gotten to all of them! \n", 712 | "\n", 713 | "In practice, some implementations of RSA use a more centralized authority and others rely on a web of trust. Cryptography requires a clever application of modular arithmetic (in Diffie-Hellman, RSA, and many other systems), but also a meticulous approach to implementation. Often the challenges of implementation introduce new problems in number theory." 714 | ] 715 | }, 716 | { 717 | "cell_type": "markdown", 718 | "metadata": {}, 719 | "source": [ 720 | "### Digital signatures\n", 721 | "\n", 722 | "A variant of RSA is used to \"digitally sign\" a document. Not worrying about keeping a message private for now, suppose that Alice wants to send Bob a message and **sign** the message in such a way that Bob can be confident it was sent by Alice. \n", 723 | "\n", 724 | "Alice can digitally sign her message by first **hashing** the message and then encrypting the hash using her **private key** (previously the *public key* was used for encryption -- this is different!). Hashing a message is an irreversible process that turns a message of possibly long length into a nonsense-message of typically fixed length, in such a way that the original message cannot be recovered from the nonsense-message. \n", 725 | "\n", 726 | "There is a science to secure hashing, which we don't touch on here. Instead, we import the `sha512` hashing function from the Python standard package `hashlib`. The input to `sha512` is a string of arbitrary length, and the output is a sequence of 512 bits. Here in Python 3, we also must specify the Unicode encoding (`utf-8`) for the string to be hashed. One can convert the 512 bits of hash into 64 bytes (512/8 = 64) which can be viewed as a 64-character string via ASCII. This 64-byte string is called the *digest* of the hash. It's all very biological. Note that many of the characters won't display very nicely, since they are out of the code range 32-126!" 727 | ] 728 | }, 729 | { 730 | "cell_type": "code", 731 | "execution_count": null, 732 | "metadata": {}, 733 | "outputs": [], 734 | "source": [ 735 | "from hashlib import sha512\n", 736 | "\n", 737 | "print(sha512(\"I like sweet potato hash.\".encode('utf-8')).digest()) # A 64-character string of hash." 738 | ] 739 | }, 740 | { 741 | "cell_type": "markdown", 742 | "metadata": {}, 743 | "source": [ 744 | "Hashes are designed to be irreversible. Nobody should be able to reverse the hashing process and recover the original string ('I like sweet potato hash') from the output of sha512. Moreover, hashes should avoid collisions -- although different input strings *can* yield the same hashed result, such \"collisions\" should be exceedingly rare in practice. You can read more about [SHA-512 and others at Wikipedia](https://en.wikipedia.org/wiki/SHA-2).\n", 745 | "\n", 746 | "Now, if Alice wishes to sign a message `m`, and send it to Bob, she goes through the following steps (in the RSA signature protocol).\n", 747 | "\n", 748 | "1. Alice hashes her message using a method such as SHA-512. Let `h` be the resulting hash.\n", 749 | "\n", 750 | "2. Alice **encrypts** the hash by computing $s = h^f$ modulo $N$. Here $f$ is the multiplicative inverse of $e$ modulo $\\phi(N)$, just as it was in RSA encryption. Note that this step requires knowledge of the private key $(p,q)$ to compute $\\phi(N)$ to compute $f$. Hence only Alice can encrypt the has in this way.\n", 751 | "\n", 752 | "3. Alice sends this encrypted hash along with her message to Bob, along with a note that she signed it using SHA-512 and her RSA key (without revealing her private keys, of course!).\n", 753 | "\n", 754 | "When Bob receives the (plaintext) message $m$ and signature $s$, he carries out the following authentication process.\n", 755 | "\n", 756 | "1. Bob computes $s^e$ modulo $N$. Since $s^e = h^{fe} = h$ modulo $N$, Bob now has the hash of the message $h$. \n", 757 | "\n", 758 | "2. Bob also computes the SHA-512 hash of the received message $m$, and compares it to the has he computed in step 1. If they match, then Alice indeed signed the message he received.\n", 759 | "\n", 760 | "We leave implementation of this process to the exercises." 761 | ] 762 | }, 763 | { 764 | "cell_type": "markdown", 765 | "metadata": {}, 766 | "source": [ 767 | "### Exercises\n", 768 | "\n", 769 | "1. Why might the exponent $e = 65537$ be a computationally convenient choice? Consider Pingala's algorithm.\n", 770 | "\n", 771 | "2. What would happen if the message $m$ encrypted by RSA were *equal* to one of these primes of the private key? How might such an occurrence be avoided, and is this something to be concerned about in practice?\n", 772 | "\n", 773 | "3. Look at the technical document [on OpenPGP](https://tools.ietf.org/html/rfc4880), and try to figure out how RSA and/or other cryptosystems are being used and implemented in practice. Write a 1-2 paragraph nontechnical summary of your findings.\n", 774 | "\n", 775 | "4. Suppose that you choose $M$ prime numbers at random between $2^{b-1}$ and $2^{b}$. Assuming that prime numbers near $x$ have a density $1 / \\log(x)$, estimate the probability that there is a \"collision\" -- that at least two of the $M$ prime numbers are the same. What is this probability when $b = 512$ and $M$ is two billion? (E.g., if a billion people use a pair of 512-bit private keys). Look up the \"Birthday Problem\" for some hints if you haven't seen this before.\n", 776 | "\n", 777 | "5. Create a function `sign(message, p,q,N,e)` to carry out the RSA signature protocol described above, based on a private key $(p,q)$ with public key $(N,e)$. Create a function `verify(message, signature, N, e)` to verify a signed message. Use the SHA-512 algorithm throughout, and check that your functions work.\n", 778 | "\n" 779 | ] 780 | }, 781 | { 782 | "cell_type": "code", 783 | "execution_count": null, 784 | "metadata": {}, 785 | "outputs": [], 786 | "source": [] 787 | } 788 | ], 789 | "metadata": { 790 | "kernelspec": { 791 | "display_name": "Python 3", 792 | "language": "python", 793 | "name": "python3" 794 | }, 795 | "language_info": { 796 | "codemirror_mode": { 797 | "name": "ipython", 798 | "version": 3 799 | }, 800 | "file_extension": ".py", 801 | "mimetype": "text/x-python", 802 | "name": "python", 803 | "nbconvert_exporter": "python", 804 | "pygments_lexer": "ipython3", 805 | "version": "3.6.4" 806 | } 807 | }, 808 | "nbformat": 4, 809 | "nbformat_minor": 1 810 | } 811 | -------------------------------------------------------------------------------- /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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | -------------------------------------------------------------------------------- /My First Python Notebook.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# A brief introduction to Jupyter Notebooks for Python." 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "This is a Jupyter notebook. **Python** is a programming language, and a **Jupyter notebook** is an interactive document which contains text (like what you're reading now) and Python code. Jupyter notebooks will be used throughout the tutorial, and this is a brief introduction to the interface.\n", 15 | "\n", 16 | "## Table of Contents\n", 17 | "\n", 18 | "1. [Notebook cells](#cells)\n", 19 | "2. [Markdown syntax](#markdown)\n", 20 | "3. [Saving, loading, printing](#files)" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "" 28 | ] 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "metadata": {}, 33 | "source": [ 34 | "## Notebook cells" 35 | ] 36 | }, 37 | { 38 | "cell_type": "markdown", 39 | "metadata": {}, 40 | "source": [ 41 | "Click inside the cell below, in the box to the right of the `In []:` prompt. A border should appear around the cell, with a green bar at the left, indicating that it's active. Then press *shift-Enter* (hold down the shift key while pressing the Enter key) on the keyboard to **evaluate** the cell. " 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "metadata": { 48 | "collapsed": false 49 | }, 50 | "outputs": [], 51 | "source": [ 52 | "2+2" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "If an output message like `Out[1]: 4` appeared, then everything is working correctly!" 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "metadata": {}, 65 | "source": [ 66 | "Jupyter notebooks are built out of **cells**. There are two primary types of cells: **Markdown cells** and **Code cells**. Textual content will be contained in Markdown cells like this one. Programming content will be contained in Code cells, like the `2+2` cell above.\n", 67 | "\n", 68 | "If a cell has a green border, that means that you're currently editing it. If it has a blue border, that means that the cell is selected (and can be cut and pasted, etc.) but not in edit-mode. Otherwise it is not active.\n", 69 | "\n", 70 | "To edit a Code cell, click anywhere within its evaluation box. For example, you can click inside the `2+2` cell, change the numbers to `2+3` and re-evaluate with *shift-Enter*. \n", 71 | "\n", 72 | "To edit a Markdown cell like this one, double-click anywhere within its body. You can write Markdown just like any text document, for the most part. When you're done editing a Markdown cell, press *shift-Enter*.\n", 73 | "\n", 74 | "To change a selected cell from Code to Markdown or back again, you should see a dropdown menu with \"Markdown\" or \"Code\" visible, just above your notebook interface. Just drop down to select the type of the cell. For practice, select the cell below to a Markdown cell, and write a sentence or two. Complete it with a *shift-Enter*." 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": null, 80 | "metadata": { 81 | "collapsed": true 82 | }, 83 | "outputs": [], 84 | "source": [ 85 | "# Change this cell to a Markdown cell, and write something." 86 | ] 87 | }, 88 | { 89 | "cell_type": "markdown", 90 | "metadata": {}, 91 | "source": [ 92 | "Now, change the cell below to a Code cell, and use it to compute `999 * 999`." 93 | ] 94 | }, 95 | { 96 | "cell_type": "markdown", 97 | "metadata": {}, 98 | "source": [ 99 | "(I'm a markdown cell. Change me to a Code cell and compute `999*999`)" 100 | ] 101 | }, 102 | { 103 | "cell_type": "markdown", 104 | "metadata": {}, 105 | "source": [ 106 | "Often you'll want to **insert a new cell** above or below a given cell. To do this, you need to select the cell in one of the following ways. Select a Code cell with a single click **outside** of its evaluation box, e.g., click where it says `In [ ]:`. Select a Markdown cell with a single-click anywhere in its body.\n", 107 | "\n", 108 | "If you have selected the cell correctly, a blue border should be visible around it. Once the blue border is visible, you can add a new cell **above** it by pressing the **a** key on the keyboard. You can add a new cell **below** it by pressing the **b** key on the keyboard. Try to add a new cell above and below the Markdown cell below. The newly created cells are probably Code cells by default.\n", 109 | "\n", 110 | "Instead of **a** or **b**, you can also press **x**. That will delete the cell, so be careful and save often." 111 | ] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "metadata": {}, 116 | "source": [ 117 | "(I'm a markdown cell. Add a new cell above and below me.)" 118 | ] 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "metadata": {}, 123 | "source": [ 124 | "A quick note: there are a few **invisible cells** in this notebook, and in other notebooks in the tutorial. In fact, one of these sneaky cells is just below this one! It's a Markdown cell, as you will see if you double-click it. Its content is ``, which is a snippet of HTML code. This is a little placeholder, which enables the links in the table of contents. Don't change those Markdown cells, unless you want to break the links in the table of contents." 125 | ] 126 | }, 127 | { 128 | "cell_type": "markdown", 129 | "metadata": {}, 130 | "source": [ 131 | "" 132 | ] 133 | }, 134 | { 135 | "cell_type": "markdown", 136 | "metadata": {}, 137 | "source": [ 138 | "## Basic Markdown for Jupyter notebooks" 139 | ] 140 | }, 141 | { 142 | "cell_type": "markdown", 143 | "metadata": {}, 144 | "source": [ 145 | "You will learn more about Python code in the tutorial. As you are learning, you should experiment in code cells, and write answers to questions and other notes in markdown cells. Markdown is a neat text-editing language, a sort of shorthand that extends HTML. Here is a brief guide to typing in Markdown." 146 | ] 147 | }, 148 | { 149 | "cell_type": "markdown", 150 | "metadata": {}, 151 | "source": [ 152 | "Most of the time, you can type Markdown just like any old text document. One little difference is that to start a new line, you have to insert an extra empty line in the Markdown. Double-click this cell to see how the new paragraph was started below. \n", 153 | "\n", 154 | "Markdown has many more features that you'll notice in this document: there are different typefaces, lists, headings, links, and more. " 155 | ] 156 | }, 157 | { 158 | "cell_type": "markdown", 159 | "metadata": {}, 160 | "source": [ 161 | "### Typefaces\n", 162 | "\n", 163 | "To change from plain text to *italics* or to **boldface**, you surround the text by asterisks or double-asterisks. Double-click inside this Markdown cell to see how it was done! Then insert a new Markdown cell below this one to experiment. Strictly speaking, the single-asterisks are used to convert to the HTML `` tag, which places emphasis on text. The double-asterisks convert to the HTML `` tag, which is often boldfaced. But different web-browsers behave differently." 164 | ] 165 | }, 166 | { 167 | "cell_type": "markdown", 168 | "metadata": {}, 169 | "source": [ 170 | "### Lists\n", 171 | "\n", 172 | "Often it is useful to make lists. The two kinds of lists we'll use are numbered lists and unnumbered lists. These are easy in Markdown. For a numbered list, just start each new line with a number. Double-click this cell to see how it was done.\n", 173 | "\n", 174 | "1. This is the first line.\n", 175 | "2. This is the second line.\n", 176 | "3. This is the third line." 177 | ] 178 | }, 179 | { 180 | "cell_type": "markdown", 181 | "metadata": {}, 182 | "source": [ 183 | "For an unnumbered (bulleted) list, start each new line with a dash `-` (a few other symbols work too). Double-click this cell to see how it was done.\n", 184 | "\n", 185 | "- This is the first line.\n", 186 | "- This is the second line.\n", 187 | "- This is the third line.\n", 188 | "\n", 189 | "Now I'm back to ordinary text again." 190 | ] 191 | }, 192 | { 193 | "cell_type": "markdown", 194 | "metadata": {}, 195 | "source": [ 196 | "You can nest your lists. But people get too attached to nested hierarchies in their writing and presentations. Lists have their place, but paragraphs should be more common. If you must nest a list, double-click this cell to see how it was done, with a bit of indentation. \n", 197 | "\n", 198 | "- This is the first line.\n", 199 | " - This is the first subline within the first line.\n", 200 | " - This is the second subline within the first line.\n", 201 | "- This is the second line.\n", 202 | "- This is the third line.\n", 203 | "\n", 204 | "Now I'm back to ordinary text again." 205 | ] 206 | }, 207 | { 208 | "cell_type": "markdown", 209 | "metadata": {}, 210 | "source": [ 211 | "### Headings\n", 212 | "\n", 213 | "There are different levels of headings, i.e., headings, subheadings, etc., which typically render as boldface text of different sizes. To make a top-level heading, a single hashtag `#` is used. The next level heading is created with a double hashtag `##`, and so on. Double-click this cell to see how it was done.\n", 214 | "\n", 215 | "# A top-level heading.\n", 216 | "## The next-level heading.\n", 217 | "### A third-level heading.\n", 218 | "#### A fourth-level heading. " 219 | ] 220 | }, 221 | { 222 | "cell_type": "markdown", 223 | "metadata": {}, 224 | "source": [ 225 | "### Links\n", 226 | "\n", 227 | "Finally, we discuss how to insert web-links in your Markdown code. For example, here is a [link to the webpage to buy An Illustrated Theory of Numbers](http://bookstore.ams.org/mbk-105). The general syntax is that the displayed text goes in brackets followed by the URL (web address) in parentheses. Double-click this cell to see how it was done." 228 | ] 229 | }, 230 | { 231 | "cell_type": "markdown", 232 | "metadata": {}, 233 | "source": [ 234 | "### Conclusion\n", 235 | "\n", 236 | "There is much much more you can do with Markdown. In fact, Markdown is a superset of HTML, so you can put just about any basic web content in a Markdown cell. A quick google search will turn up lots of Markdown guides, and it's best to search for Markdown and Jupyter to find a guide for Jupyter's particular flavor of Markdown (which differs a bit from WordPress markdown, for example). " 237 | ] 238 | }, 239 | { 240 | "cell_type": "markdown", 241 | "metadata": { 242 | "collapsed": true 243 | }, 244 | "source": [ 245 | "" 246 | ] 247 | }, 248 | { 249 | "cell_type": "markdown", 250 | "metadata": {}, 251 | "source": [ 252 | "## Saving, loading, and printing notebooks" 253 | ] 254 | }, 255 | { 256 | "cell_type": "markdown", 257 | "metadata": {}, 258 | "source": [ 259 | "You can save, load, and print Jupyter notebooks. In fact, it's probably a good time to save this notebook since you've edited the markdown so far. Go to \"File...Save and Checkpoint\" (the File menu just under \"Jupyter\") to save your notebook so far.\n", 260 | "\n" 261 | ] 262 | }, 263 | { 264 | "cell_type": "markdown", 265 | "metadata": {}, 266 | "source": [ 267 | "The standard notebook file format is `.ipynb` which stands for \"iPython Notebook\", since Jupyter used to be called iPython. If you go to \"File...Download as...\", then \"IPython Notebook\" will be the top choice. You will always be able to reload your notebook and edit it, if you save it as an iPython Notebook.\n", 268 | "\n", 269 | "You may also want to save a copy as an `.html` file. HTML is the code used to render webpages, and so it's good for sharing with anyone with a web browser. Also, your web browser can probably print the HTML file nicely, so it's a good format for printing. You can go directly to \"File...Print preview\" to see what the notebook will look like when printed.\n", 270 | "\n", 271 | "To open a Python notebook, you can go to \"File...Open\" or you can return to your original Jupyter tab (if it's still there) and browse directories to find notebook files. But Jupyter must be started to load python notebooks on your computer.\n", 272 | "\n", 273 | "\n", 274 | "\n" 275 | ] 276 | }, 277 | { 278 | "cell_type": "markdown", 279 | "metadata": {}, 280 | "source": [ 281 | "One more tool to learn about is [GitHub](https://github.com/). GitHub is a website which allows users to share and develop software of all sorts. It's used for collaborative software development, and has many desirable features like \"versioning\" (keeping track of versions along the way as various parties make edits). You can freely use GitHub to store your Python notebooks. GitHub takes a bit of practice, but it's worth the effort in the long run. \n", 282 | "\n", 283 | "The tutorial notebooks are stored on GitHub for a few reasons. First, they can be easily edited and improved. Second, they become freely and publicly available. Go to [my GitHub page](https://github.com/MartyWeissman/Python-for-number-theory) to see them! Third, even though they are stored in `.ipynb` format, anyone can view Python notebooks on the web using the [Jupyter Notebook Viewer](https://nbviewer.jupyter.org/). For example, you can use the Jupyter Notebook Viewer to see [this notebook online](https://nbviewer.jupyter.org/github/MartyWeissman/Python-for-number-theory/blob/master/My%20First%20Python%20Notebook.ipynb)." 284 | ] 285 | }, 286 | { 287 | "cell_type": "markdown", 288 | "metadata": {}, 289 | "source": [ 290 | "Now you know more than enough to begin the Python tutorials. Download the notebooks and **happy programming**!" 291 | ] 292 | } 293 | ], 294 | "metadata": { 295 | "kernelspec": { 296 | "display_name": "Python 2", 297 | "language": "python", 298 | "name": "python2" 299 | }, 300 | "language_info": { 301 | "codemirror_mode": { 302 | "name": "ipython", 303 | "version": 2 304 | }, 305 | "file_extension": ".py", 306 | "mimetype": "text/x-python", 307 | "name": "python", 308 | "nbconvert_exporter": "python", 309 | "pygments_lexer": "ipython2", 310 | "version": "2.7.13" 311 | } 312 | }, 313 | "nbformat": 4, 314 | "nbformat_minor": 0 315 | } 316 | -------------------------------------------------------------------------------- /My First Python3 Notebook.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# A brief introduction to Jupyter Notebooks for Python 3." 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "This is a Jupyter notebook. **Python** is a programming language, and a **Jupyter notebook** is an interactive document which contains text (like what you're reading now) and Python code. Jupyter notebooks will be used throughout the tutorial, and this is a brief introduction to the interface.\n", 15 | "\n", 16 | "## Table of Contents\n", 17 | "\n", 18 | "1. [Notebook cells](#cells)\n", 19 | "2. [Markdown syntax](#markdown)\n", 20 | "3. [Saving, loading, printing](#files)" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "" 28 | ] 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "metadata": {}, 33 | "source": [ 34 | "## Notebook cells" 35 | ] 36 | }, 37 | { 38 | "cell_type": "markdown", 39 | "metadata": {}, 40 | "source": [ 41 | "Click inside the cell below, in the box to the right of the `In []:` prompt. A border should appear around the cell, with a green bar at the left, indicating that it's active. Then press *shift-Enter* (hold down the shift key while pressing the Enter key) on the keyboard to **evaluate** the cell. " 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "2+2" 51 | ] 52 | }, 53 | { 54 | "cell_type": "markdown", 55 | "metadata": {}, 56 | "source": [ 57 | "If an output message like `Out[1]: 4` appeared, then everything is working correctly!" 58 | ] 59 | }, 60 | { 61 | "cell_type": "markdown", 62 | "metadata": {}, 63 | "source": [ 64 | "Jupyter notebooks are built out of **cells**. There are two primary types of cells: **Markdown cells** and **Code cells**. Textual content will be contained in Markdown cells like this one. Programming content will be contained in Code cells, like the `2+2` cell above.\n", 65 | "\n", 66 | "If a cell has a green border, that means that you're currently editing it. If it has a blue border, that means that the cell is selected (and can be cut and pasted, etc.) but not in edit-mode. Otherwise it is not active.\n", 67 | "\n", 68 | "To edit a Code cell, click anywhere within its evaluation box. For example, you can click inside the `2+2` cell, change the numbers to `2+3` and re-evaluate with *shift-Enter*. \n", 69 | "\n", 70 | "To edit a Markdown cell like this one, double-click anywhere within its body. You can write Markdown just like any text document, for the most part. When you're done editing a Markdown cell, press *shift-Enter*.\n", 71 | "\n", 72 | "To change a selected cell from Code to Markdown or back again, you should see a dropdown menu with \"Markdown\" or \"Code\" visible, just above your notebook interface. Just drop down to select the type of the cell. For practice, select the cell below to a Markdown cell, and write a sentence or two. Complete it with a *shift-Enter*." 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": null, 78 | "metadata": {}, 79 | "outputs": [], 80 | "source": [ 81 | "# Change this cell to a Markdown cell, and write something." 82 | ] 83 | }, 84 | { 85 | "cell_type": "markdown", 86 | "metadata": {}, 87 | "source": [ 88 | "Now, change the cell below to a Code cell, and use it to compute `999 * 999`." 89 | ] 90 | }, 91 | { 92 | "cell_type": "markdown", 93 | "metadata": {}, 94 | "source": [ 95 | "(I'm a markdown cell. Change me to a Code cell and compute `999*999`)" 96 | ] 97 | }, 98 | { 99 | "cell_type": "markdown", 100 | "metadata": {}, 101 | "source": [ 102 | "Often you'll want to **insert a new cell** above or below a given cell. To do this, you need to select the cell in one of the following ways. Select a Code cell with a single click **outside** of its evaluation box, e.g., click where it says `In [ ]:`. Select a Markdown cell with a single-click anywhere in its body.\n", 103 | "\n", 104 | "If you have selected the cell correctly, a blue border should be visible around it. Once the blue border is visible, you can add a new cell **above** it by pressing the **a** key on the keyboard. You can add a new cell **below** it by pressing the **b** key on the keyboard. Try to add a new cell above and below the Markdown cell below. The newly created cells are probably Code cells by default.\n", 105 | "\n", 106 | "Instead of **a** or **b**, you can also press **x**. That will delete the cell, so be careful and save often." 107 | ] 108 | }, 109 | { 110 | "cell_type": "markdown", 111 | "metadata": {}, 112 | "source": [ 113 | "(I'm a markdown cell. Add a new cell above and below me.)" 114 | ] 115 | }, 116 | { 117 | "cell_type": "markdown", 118 | "metadata": {}, 119 | "source": [ 120 | "A quick note: there are a few **invisible cells** in this notebook, and in other notebooks in the tutorial. In fact, one of these sneaky cells is just below this one! It's a Markdown cell, as you will see if you double-click it. Its content is ``, which is a snippet of HTML code. This is a little placeholder, which enables the links in the table of contents. Don't change those Markdown cells, unless you want to break the links in the table of contents." 121 | ] 122 | }, 123 | { 124 | "cell_type": "markdown", 125 | "metadata": {}, 126 | "source": [ 127 | "" 128 | ] 129 | }, 130 | { 131 | "cell_type": "markdown", 132 | "metadata": {}, 133 | "source": [ 134 | "## Basic Markdown for Jupyter notebooks" 135 | ] 136 | }, 137 | { 138 | "cell_type": "markdown", 139 | "metadata": {}, 140 | "source": [ 141 | "You will learn more about Python code in the tutorial. As you are learning, you should experiment in code cells, and write answers to questions and other notes in markdown cells. Markdown is a neat text-editing language, a sort of shorthand that extends HTML. Here is a brief guide to typing in Markdown." 142 | ] 143 | }, 144 | { 145 | "cell_type": "markdown", 146 | "metadata": {}, 147 | "source": [ 148 | "Most of the time, you can type Markdown just like any old text document. One little difference is that to start a new line, you have to insert an extra empty line in the Markdown. Double-click this cell to see how the new paragraph was started below. \n", 149 | "\n", 150 | "Markdown has many more features that you'll notice in this document: there are different typefaces, lists, headings, links, and more. " 151 | ] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "metadata": {}, 156 | "source": [ 157 | "### Typefaces\n", 158 | "\n", 159 | "To change from plain text to *italics* or to **boldface**, you surround the text by asterisks or double-asterisks. Double-click inside this Markdown cell to see how it was done! Then insert a new Markdown cell below this one to experiment. Strictly speaking, the single-asterisks are used to convert to the HTML `` tag, which places emphasis on text. The double-asterisks convert to the HTML `` tag, which is often boldfaced. But different web-browsers behave differently." 160 | ] 161 | }, 162 | { 163 | "cell_type": "markdown", 164 | "metadata": {}, 165 | "source": [ 166 | "### Lists\n", 167 | "\n", 168 | "Often it is useful to make lists. The two kinds of lists we'll use are numbered lists and unnumbered lists. These are easy in Markdown. For a numbered list, just start each new line with a number. Double-click this cell to see how it was done.\n", 169 | "\n", 170 | "1. This is the first line.\n", 171 | "2. This is the second line.\n", 172 | "3. This is the third line." 173 | ] 174 | }, 175 | { 176 | "cell_type": "markdown", 177 | "metadata": {}, 178 | "source": [ 179 | "For an unnumbered (bulleted) list, start each new line with a dash `-` (a few other symbols work too). Double-click this cell to see how it was done.\n", 180 | "\n", 181 | "- This is the first line.\n", 182 | "- This is the second line.\n", 183 | "- This is the third line.\n", 184 | "\n", 185 | "Now I'm back to ordinary text again." 186 | ] 187 | }, 188 | { 189 | "cell_type": "markdown", 190 | "metadata": {}, 191 | "source": [ 192 | "You can nest your lists. But people get too attached to nested hierarchies in their writing and presentations. Lists have their place, but paragraphs should be more common. If you must nest a list, double-click this cell to see how it was done, with a bit of indentation. \n", 193 | "\n", 194 | "- This is the first line.\n", 195 | " - This is the first subline within the first line.\n", 196 | " - This is the second subline within the first line.\n", 197 | "- This is the second line.\n", 198 | "- This is the third line.\n", 199 | "\n", 200 | "Now I'm back to ordinary text again." 201 | ] 202 | }, 203 | { 204 | "cell_type": "markdown", 205 | "metadata": {}, 206 | "source": [ 207 | "### Headings\n", 208 | "\n", 209 | "There are different levels of headings, i.e., headings, subheadings, etc., which typically render as boldface text of different sizes. To make a top-level heading, a single hashtag `#` is used. The next level heading is created with a double hashtag `##`, and so on. Double-click this cell to see how it was done.\n", 210 | "\n", 211 | "# A top-level heading.\n", 212 | "## The next-level heading.\n", 213 | "### A third-level heading.\n", 214 | "#### A fourth-level heading. " 215 | ] 216 | }, 217 | { 218 | "cell_type": "markdown", 219 | "metadata": {}, 220 | "source": [ 221 | "### Links\n", 222 | "\n", 223 | "Finally, we discuss how to insert web-links in your Markdown code. For example, here is a [link to the webpage to buy An Illustrated Theory of Numbers](http://bookstore.ams.org/mbk-105). The general syntax is that the displayed text goes in brackets followed by the URL (web address) in parentheses. Double-click this cell to see how it was done." 224 | ] 225 | }, 226 | { 227 | "cell_type": "markdown", 228 | "metadata": {}, 229 | "source": [ 230 | "### Conclusion\n", 231 | "\n", 232 | "There is much much more you can do with Markdown. In fact, Markdown is a superset of HTML, so you can put just about any basic web content in a Markdown cell. A quick google search will turn up lots of Markdown guides, and it's best to search for Markdown and Jupyter to find a guide for Jupyter's particular flavor of Markdown (which differs a bit from WordPress markdown, for example). " 233 | ] 234 | }, 235 | { 236 | "cell_type": "markdown", 237 | "metadata": { 238 | "collapsed": true 239 | }, 240 | "source": [ 241 | "" 242 | ] 243 | }, 244 | { 245 | "cell_type": "markdown", 246 | "metadata": {}, 247 | "source": [ 248 | "## Saving, loading, and printing notebooks" 249 | ] 250 | }, 251 | { 252 | "cell_type": "markdown", 253 | "metadata": {}, 254 | "source": [ 255 | "You can save, load, and print Jupyter notebooks. In fact, it's probably a good time to save this notebook since you've edited the markdown so far. Go to \"File...Save and Checkpoint\" (the File menu just under \"Jupyter\") to save your notebook so far.\n", 256 | "\n" 257 | ] 258 | }, 259 | { 260 | "cell_type": "markdown", 261 | "metadata": {}, 262 | "source": [ 263 | "The standard notebook file format is `.ipynb` which stands for \"iPython Notebook\", since Jupyter used to be called iPython. If you go to \"File...Download as...\", then \"IPython Notebook\" will be the top choice. You will always be able to reload your notebook and edit it, if you save it as an iPython Notebook.\n", 264 | "\n", 265 | "You may also want to save a copy as an `.html` file. HTML is the code used to render webpages, and so it's good for sharing with anyone with a web browser. Also, your web browser can probably print the HTML file nicely, so it's a good format for printing. You can go directly to \"File...Print preview\" to see what the notebook will look like when printed.\n", 266 | "\n", 267 | "To open a Python notebook, you can go to \"File...Open\" or you can return to your original Jupyter tab (if it's still there) and browse directories to find notebook files. But Jupyter must be started to load python notebooks on your computer.\n", 268 | "\n", 269 | "\n", 270 | "\n" 271 | ] 272 | }, 273 | { 274 | "cell_type": "markdown", 275 | "metadata": {}, 276 | "source": [ 277 | "One more tool to learn about is [GitHub](https://github.com/). GitHub is a website which allows users to share and develop software of all sorts. It's used for collaborative software development, and has many desirable features like \"versioning\" (keeping track of versions along the way as various parties make edits). You can freely use GitHub to store your Python notebooks. GitHub takes a bit of practice, but it's worth the effort in the long run. \n", 278 | "\n", 279 | "The tutorial notebooks are stored on GitHub for a few reasons. First, they can be easily edited and improved. Second, they become freely and publicly available. Go to [my GitHub page](https://github.com/MartyWeissman/Python-for-number-theory) to see them! Third, even though they are stored in `.ipynb` format, anyone can view Python notebooks on the web using the [Jupyter Notebook Viewer](https://nbviewer.jupyter.org/). For example, you can use the Jupyter Notebook Viewer to see [this notebook online](https://nbviewer.jupyter.org/github/MartyWeissman/Python-for-number-theory/blob/master/My%20First%20Python%20Notebook.ipynb)." 280 | ] 281 | }, 282 | { 283 | "cell_type": "markdown", 284 | "metadata": {}, 285 | "source": [ 286 | "Now you know more than enough to begin the Python tutorials. Download the notebooks and **happy programming**!" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": null, 292 | "metadata": {}, 293 | "outputs": [], 294 | "source": [] 295 | } 296 | ], 297 | "metadata": { 298 | "kernelspec": { 299 | "display_name": "Python 3", 300 | "language": "python", 301 | "name": "python3" 302 | }, 303 | "language_info": { 304 | "codemirror_mode": { 305 | "name": "ipython", 306 | "version": 3 307 | }, 308 | "file_extension": ".py", 309 | "mimetype": "text/x-python", 310 | "name": "python", 311 | "nbconvert_exporter": "python", 312 | "pygments_lexer": "ipython3", 313 | "version": "3.6.4" 314 | } 315 | }, 316 | "nbformat": 4, 317 | "nbformat_minor": 1 318 | } 319 | -------------------------------------------------------------------------------- /P3wNT Notebook 7.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Part 7: The RSA Cryptosystem in Python 3.x" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "In the previous notebook, we studied a few basic ciphers together with Diffie-Hellman key exchange. The Vigenère cipher we studied uses a **secret key** for encrypting and decrypting messages. The same key is used for both encryption and decryption, so we say it is a **symmetric key** cipher. In order for two parties to share the same secret key, we studied the Diffie-Hellman protocol, whose security rests on the difficulty of the discrete logarithm problem.\n", 15 | "\n", 16 | "Although this represents progress towards secure communication, it is particularly vulnerable to problems of authentication. For example, imagine a \"man-in-the-middle attack\": Alice and Bob wish to communicate securely, and begin the Diffie-Hellman protocol over an insecure line. But **Eve** has intercepted the line. To Alice, she pretends to be Bob, and to Bob, she pretends to be Alice. She goes through the Diffie-Hellman protocol with each, obtaining two secret keys, and decrypting/encrypting messages as they pass through her computer. In this way, Alice and Bob think they are talking to each other, but Eve is just passing (and understanding) their messages the whole time!\n", 17 | "\n", 18 | "To thwart such an attack, we need some type of authentication. We need something **asymmetric** -- something one person can do that no other person can do, like a verifiable signature, so that we can be sure we're communicating with the intended person. For such a purpose, we introduce the RSA cryptosystem. Computationally based on modular exponentiation, its security rests on the difficulty of factoring large numbers.\n", 19 | "\n", 20 | "The material in this notebook complements Chapter 7 of [An Illustrated Theory of Numbers](http://illustratedtheoryofnumbers.com/index.html)." 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "## Table of Contents\n", 28 | "\n", 29 | "- [Euler's theorem and modular roots](#euler)\n", 30 | "- [The RSA protocol](#RSA)" 31 | ] 32 | }, 33 | { 34 | "cell_type": "markdown", 35 | "metadata": {}, 36 | "source": [ 37 | "" 38 | ] 39 | }, 40 | { 41 | "cell_type": "markdown", 42 | "metadata": {}, 43 | "source": [ 44 | "## Euler's Theorem and Modular Roots\n", 45 | "\n", 46 | "Recall Fermat's Little Theorem: if $p$ is prime and $GCD(a,p) = 1$, then $a^{p-1} \\equiv 1$ mod $p$. This is a special case of Euler's theorem, which holds for any modulus $m$.\n", 47 | "\n", 48 | "### Euler's theorem and the totient\n", 49 | "\n", 50 | "Euler's theorem states: if $m$ is a positive integer and $GCD(a,m) = 1$, then $a^{\\phi(m)} \\equiv 1$ mod $m$. Here $\\phi(m)$ denotes the **totient** of $m$, which is the number of elements of $\\{ 1,...,m \\}$ which are coprime to $m$. We give a brute force implementation of the totient first, using our old Euclidean algorithm code for the GCD." 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": {}, 57 | "outputs": [], 58 | "source": [ 59 | "def GCD(a,b):\n", 60 | " while b: # Recall that != means \"not equal to\".\n", 61 | " a, b = b, a % b\n", 62 | " return abs(a)\n", 63 | "\n", 64 | "def totient(m):\n", 65 | " tot = 0 # The running total.\n", 66 | " j = 0\n", 67 | " while j < m: # We go up to m, because the totient of 1 is 1 by convention.\n", 68 | " j = j + 1 # Last step of while loop: j = m-1, and then j = j+1, so j = m.\n", 69 | " if GCD(j,m) == 1:\n", 70 | " tot = tot + 1\n", 71 | " return tot" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "totient(17) # The totient of a prime p should be p-1." 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "metadata": {}, 87 | "outputs": [], 88 | "source": [ 89 | "totient(1000)" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": null, 95 | "metadata": {}, 96 | "outputs": [], 97 | "source": [ 98 | "totient(1) # Check a borderline case, to make sure we didn't make an off-by-one error." 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "17**totient(1000) % 1000 # Let's demonstrate Euler's theorem. Note GCD(17,1000) = 1." 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": null, 113 | "metadata": {}, 114 | "outputs": [], 115 | "source": [ 116 | "pow(17,totient(1000),1000) # A more efficient version, using the pow command." 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": null, 122 | "metadata": {}, 123 | "outputs": [], 124 | "source": [ 125 | "%timeit totient(123456)" 126 | ] 127 | }, 128 | { 129 | "cell_type": "markdown", 130 | "metadata": {}, 131 | "source": [ 132 | "The totient is a **multiplicative function**, meaning that if $GCD(a,b) = 1$, then $\\phi(ab) = \\phi(a) \\phi(b)$. Therefore, the totient of number can be found quickly from the totient of the prime powers within its decomposition. We can re-implement the totient using our functions for prime decomposition and multiplicative functions from [Notebook 4](http://illustratedtheoryofnumbers.com/prog.html#notebooks)." 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": null, 138 | "metadata": {}, 139 | "outputs": [], 140 | "source": [ 141 | "from math import sqrt # We'll want to use the square root.\n", 142 | "\n", 143 | "def smallest_factor(n):\n", 144 | " '''\n", 145 | " Gives the smallest prime factor of n.\n", 146 | " '''\n", 147 | " if n < 2:\n", 148 | " return None # No prime factors!\n", 149 | " \n", 150 | " test_factor = 2 # The smallest possible prime factor.\n", 151 | " max_factor = sqrt(n) # we don't have to search past sqrt(n).\n", 152 | " \n", 153 | " while test_factor <= max_factor:\n", 154 | " if n%test_factor == 0:\n", 155 | " return test_factor\n", 156 | " test_factor = test_factor + 1 # This could be sped up.\n", 157 | " \n", 158 | " return n # If we didn't find a factor up to sqrt(n), n itself is prime!\n", 159 | "\n", 160 | "def decompose(N):\n", 161 | " '''\n", 162 | " Gives the unique prime decomposition of a positive integer N,\n", 163 | " as a dictionary with primes as keys and exponents as values.\n", 164 | " '''\n", 165 | " current_number = N # We'll divide out factors from current_number until we get 1.\n", 166 | " decomp = {} # An empty dictionary to start.\n", 167 | " while current_number > 1:\n", 168 | " p = smallest_factor(current_number) # The smallest prime factor of the current number.\n", 169 | " if p in decomp.keys(): # Is p already in the list of keys?\n", 170 | " decomp[p] = decomp[p] + 1 # Increase the exponent (value with key p) by 1.\n", 171 | " else: # \"else\" here means \"if p is not in decomp.keys()\".\n", 172 | " decomp[p] = 1 # Creates a new entry in the dictionary, with key p and value 1.\n", 173 | " current_number = current_number // p # Factor out p.\n", 174 | " return decomp\n", 175 | "\n", 176 | "def mult_function(f_pp):\n", 177 | " '''\n", 178 | " When a function f_pp(p,e) of two arguments is input,\n", 179 | " this outputs a multiplicative function obtained from f_pp\n", 180 | " via prime decomposition.\n", 181 | " '''\n", 182 | " def f(n):\n", 183 | " D = decompose(n)\n", 184 | " result = 1\n", 185 | " for p in D:\n", 186 | " result = result * f_pp(p, D[p])\n", 187 | " return result\n", 188 | " \n", 189 | " return f" 190 | ] 191 | }, 192 | { 193 | "cell_type": "markdown", 194 | "metadata": {}, 195 | "source": [ 196 | "When $p^e$ is a prime power, the numbers among $1, \\ldots, p^e$ are coprime to $p^e$ precisely when they are **not** multiples of $p$. Therefore, the totient of a prime power is pretty easy to compute:\n", 197 | "$$\\phi(p^e) = p^e - p^{e-1} = p^{e-1} (p-1).$$\n", 198 | "We implement this, and use the multiplicative function code to complete the implementation of the totient." 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": null, 204 | "metadata": {}, 205 | "outputs": [], 206 | "source": [ 207 | "def totient_pp(p,e):\n", 208 | " return (p**(e-1)) * (p-1)" 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "metadata": {}, 214 | "source": [ 215 | "Note that for efficiency, the computation of $p^{e-1}(p-1)$ is probably faster than the computation of $p^e - p^{e-1}$ (which relies on two exponents). But Python is very smart about these sorts of things, and might do some optimization which makes the computation faster. It should be very fast anyways, in the 10-20 nanosecond range!" 216 | ] 217 | }, 218 | { 219 | "cell_type": "code", 220 | "execution_count": null, 221 | "metadata": {}, 222 | "outputs": [], 223 | "source": [ 224 | "totient = mult_function(totient_pp)" 225 | ] 226 | }, 227 | { 228 | "cell_type": "code", 229 | "execution_count": null, 230 | "metadata": {}, 231 | "outputs": [], 232 | "source": [ 233 | "totient(1000)" 234 | ] 235 | }, 236 | { 237 | "cell_type": "code", 238 | "execution_count": null, 239 | "metadata": {}, 240 | "outputs": [], 241 | "source": [ 242 | "%timeit totient(123456)" 243 | ] 244 | }, 245 | { 246 | "cell_type": "markdown", 247 | "metadata": {}, 248 | "source": [ 249 | "This should be **much** faster than the previous brute-force computation of the totient." 250 | ] 251 | }, 252 | { 253 | "cell_type": "markdown", 254 | "metadata": {}, 255 | "source": [ 256 | "### Modular roots" 257 | ] 258 | }, 259 | { 260 | "cell_type": "markdown", 261 | "metadata": {}, 262 | "source": [ 263 | "A consequence of Euler's theorem is that -- depending on the modulus -- some exponentiation can be \"reversed\" by another exponentiation, a form of taking a \"root\" in modular arithmetic. For example, if we work modulo $100$, and $GCD(a,100) = 1$, then Euler's theorem states that\n", 264 | "$$a^{40} \\equiv 1 \\text{ mod } 100.$$\n", 265 | "It follows that $a^{80} \\equiv 1$ and $a^{81} \\equiv a$, modulo $100$. Expanding this, we find\n", 266 | "$$a \\equiv a^{81} = a^{3 \\cdot 27} = (a^3)^{27} \\text{ mod } 100.$$\n", 267 | "\n", 268 | "What all this computation shows is that \"raising to the 27th power\" is like \"taking the cube root\", modulo 100 (and with appropriate bases)." 269 | ] 270 | }, 271 | { 272 | "cell_type": "code", 273 | "execution_count": null, 274 | "metadata": {}, 275 | "outputs": [], 276 | "source": [ 277 | "for b in range(20):\n", 278 | " b_cubed = pow(b,3,100)\n", 279 | " bb = pow(b_cubed,27,100)\n", 280 | " print(b, b_cubed, bb, GCD(b,100) == 1)" 281 | ] 282 | }, 283 | { 284 | "cell_type": "markdown", 285 | "metadata": {}, 286 | "source": [ 287 | "In every line ending with `True`, the first and third numbers should match. This will happen in some `False` lines too, but not reliably since Euler's theorem does not apply there.\n", 288 | "\n", 289 | "We found the exponent 27 -- reversing the cubing operation -- by an ad hoc sort of procedure. The relationship between 27 and 3, which made things work, is that\n", 290 | "$$3 \\cdot 27 \\equiv 1 \\text{ mod } 40.$$\n", 291 | "In other words, $3 \\cdot 27 = 1 + 40k$ for some (positive, in fact) integer $k$.\n", 292 | "\n", 293 | "Recalling that $40 = \\phi(100)$, this relationship and Euler's theorem imply that\n", 294 | "$$a^{3 \\cdot 27} = a^{1 + 40k} \\equiv a^1 = a \\text{ mod } 100.$$\n", 295 | "By this argument, we have the following consequence of Euler's theorem. \n", 296 | "\n", 297 | "**Theorem: ** If $GCD(a,m) = 1$, and $ef \\equiv 1$ mod $\\phi(m)$, then\n", 298 | "$$a^{ef} \\equiv a \\text{ mod } \\phi(m).$$\n", 299 | "In this way, \"raising to the $f$ power\" is like \"taking the $e$-th root\", modulo $m$. \n", 300 | "\n", 301 | "If we are given $f$, then $e$ is a **multiplicative inverse** of $f$ modulo $\\phi(m)$. In particular, such a multiplicative inverse exists if and only if $GCD(e,\\phi(m)) = 1$. The following function computes a multiplicative inverse, by adapting the `solve_LDE` function from [Notebook 2](). After all, solving $ex \\equiv 1$ mod $m$ is equivalent to solving the linear Diophantine equation $ex + my = 1$ (and only caring about the $x$-value). \n" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": null, 307 | "metadata": {}, 308 | "outputs": [], 309 | "source": [ 310 | "def mult_inverse(a,m):\n", 311 | " '''\n", 312 | " Finds the multiplicative inverse of a, mod m.\n", 313 | " If GCD(a,m) = 1, this is returned via its natural representative.\n", 314 | " Otherwise, None is returned.\n", 315 | " ''' \n", 316 | " u = a # We use u instead of dividend.\n", 317 | " v = m # We use v instead of divisor.\n", 318 | " u_hops, u_skips = 1,0 # u is built from one hop (a) and no skips.\n", 319 | " v_hops, v_skips = 0,1 # v is built from no hops and one skip (b).\n", 320 | " while v != 0: # We could just write while v:\n", 321 | " q = u // v # q stands for quotient.\n", 322 | " r = u % v # r stands for remainder. So u = q(v) + r.\n", 323 | " \n", 324 | " r_hops = u_hops - q * v_hops # Tally hops\n", 325 | " r_skips = u_skips - q * v_skips # Tally skips\n", 326 | " \n", 327 | " u,v = v,r # The new dividend,divisor is the old divisor,remainder.\n", 328 | " u_hops, v_hops = v_hops, r_hops # The new u_hops, v_hops is the old v_hops, r_hops\n", 329 | " u_skips, v_skips = v_skips, r_skips # The new u_skips, v_skips is the old v_skips, r_skips\n", 330 | " \n", 331 | " g = u # The variable g now describes the GCD of a and b.\n", 332 | " if g == 1:\n", 333 | " return u_hops % m\n", 334 | " else: # When GCD(a,m) is not 1...\n", 335 | " return None" 336 | ] 337 | }, 338 | { 339 | "cell_type": "code", 340 | "execution_count": null, 341 | "metadata": {}, 342 | "outputs": [], 343 | "source": [ 344 | "mult_inverse(3,40) # 3 times what is congruent to 1, mod 40?" 345 | ] 346 | }, 347 | { 348 | "cell_type": "code", 349 | "execution_count": null, 350 | "metadata": {}, 351 | "outputs": [], 352 | "source": [ 353 | "mult_inverse(5,40) # None should be returned." 354 | ] 355 | }, 356 | { 357 | "cell_type": "markdown", 358 | "metadata": {}, 359 | "source": [ 360 | "Let's test this out on some bigger numbers." 361 | ] 362 | }, 363 | { 364 | "cell_type": "code", 365 | "execution_count": null, 366 | "metadata": {}, 367 | "outputs": [], 368 | "source": [ 369 | "from random import randint\n", 370 | "while True:\n", 371 | " m = randint(1000000, 9999999) # a random 7-digit number\n", 372 | " e = randint(100,999) # a random 3-digit number\n", 373 | " a = randint(10,99) # a random 2-digit number\n", 374 | " if GCD(a,m) == 1:\n", 375 | " tot = totient(m)\n", 376 | " if GCD(e,tot) == 1:\n", 377 | " f = mult_inverse(e,tot)\n", 378 | " test_number = pow(a, e*f, m)\n", 379 | " print(\"Success!\")\n", 380 | " print(\"{} ^ ({} * {}) = {}, mod {}\".format(a,e,f,test_number,m))\n", 381 | " break # Escapes the loop once an example is found!" 382 | ] 383 | }, 384 | { 385 | "cell_type": "markdown", 386 | "metadata": {}, 387 | "source": [ 388 | "### Exercises\n", 389 | "\n", 390 | "1. What is the largest integer whose totient is 100? Study this by a brute force search, i.e., looping through the integers up to 10000\n", 391 | "\n", 392 | "2. For which integers $n$ is it true that $\\phi(n) = n/2$? Study this by a brute force search in order to make a conjecture. Then prove it if you can.\n", 393 | "\n", 394 | "3. Compute the totient of the numbers from 1 to 10000, and analyze the results. The totient $\\phi(n)$ is always less than $n$ when $n > 1$, but how does the ratio $\\phi(n) / n$ behave? Create a graph. What is the average value of the ratio? \n", 395 | "\n", 396 | "4. If $a^{323} \\equiv 802931$, mod $5342481$, and $GCD(a, 5342481) = 1$, and $0 < a < 5342481$, then what is $a$? \n", 397 | "\n", 398 | "5. Challenge: Create a function `superpow(x,y,z,m)` which computes $x^{y^z}$ modulo $m$ efficiently, when $GCD(x,m) = 1$ and $m$ is small enough to factor." 399 | ] 400 | }, 401 | { 402 | "cell_type": "markdown", 403 | "metadata": {}, 404 | "source": [ 405 | "" 406 | ] 407 | }, 408 | { 409 | "cell_type": "markdown", 410 | "metadata": {}, 411 | "source": [ 412 | "## The RSA protocol" 413 | ] 414 | }, 415 | { 416 | "cell_type": "markdown", 417 | "metadata": {}, 418 | "source": [ 419 | "Like Diffie-Hellman, the RSA protocol involves a series of computations in modular arithmetic, taking care to keep some numbers private while making others public. RSA was published two years after Diffie-Hellman, in 1978 by Rivest, Shamir, and Adelman (hence its name). The great advance of the RSA protocol was its **asymmetry**. While Diffie-Hellman is used for symmetric key cryptography (using the same key to encrypt and decrypt), the RSA protocol has two keys: a **public key** that can be used by anyone for encryption and a **private key** that can be used by its owner for decryption. \n", 420 | "\n", 421 | "In this way, if Alice publishes her public key online, anyone can send her an encrypted message. But as long as she keeps her private key private, **only** Alice can decrypt the messages sent to her. Such an asymmetry allows RSA to be used for authentication -- if the owner of a private key has an ability nobody else has, then this ability can be used to prove the owner's identity. In practice, this is one of the most common applications of RSA, guaranteeing that we are communicating with the intended person." 422 | ] 423 | }, 424 | { 425 | "cell_type": "markdown", 426 | "metadata": {}, 427 | "source": [ 428 | "In the RSA protocol, the **private key** is a pair of large (e.g. 512 bit) prime numbers, called $p$ and $q$. The **public key** is the pair $(N, e)$, where $N$ is defined to be the product $N = pq$ and $e$ is an auxiliary number called the exponent. The number $e$ is often (for computational efficiency and other reasons) taken to be 65537 -- the same number $e$ can be used over and over by different people. But it is absolutely crucial that the same private keys $p$ and $q$ are not used by different individuals. Individuals must create and safely keep their own private key." 429 | ] 430 | }, 431 | { 432 | "cell_type": "markdown", 433 | "metadata": {}, 434 | "source": [ 435 | "We begin with the creation of a private key $(p,q)$. We use the `SystemRandom` function (see the previous Python Notebook) to cook up cryptographically secure random numbers, and the Miller-Rabin test to certify primality." 436 | ] 437 | }, 438 | { 439 | "cell_type": "code", 440 | "execution_count": null, 441 | "metadata": {}, 442 | "outputs": [], 443 | "source": [ 444 | "from random import SystemRandom, randint\n", 445 | "\n", 446 | "def Miller_Rabin(p, base):\n", 447 | " '''\n", 448 | " Tests whether p is prime, using the given base.\n", 449 | " The result False implies that p is definitely not prime.\n", 450 | " The result True implies that p **might** be prime.\n", 451 | " It is not a perfect test!\n", 452 | " '''\n", 453 | " result = 1\n", 454 | " exponent = p-1\n", 455 | " modulus = p\n", 456 | " bitstring = bin(exponent)[2:] # Chop off the '0b' part of the binary expansion of exponent\n", 457 | " for bit in bitstring: # Iterates through the \"letters\" of the string. Here the letters are '0' or '1'.\n", 458 | " sq_result = result*result % modulus # We need to compute this in any case.\n", 459 | " if sq_result == 1:\n", 460 | " if (result != 1) and (result != exponent): # Note that exponent is congruent to -1, mod p.\n", 461 | " return False # a ROO violation occurred, so p is not prime\n", 462 | " if bit == '0':\n", 463 | " result = sq_result \n", 464 | " if bit == '1':\n", 465 | " result = (sq_result * base) % modulus\n", 466 | " if result != 1:\n", 467 | " return False # a FLT violation occurred, so p is not prime.\n", 468 | " \n", 469 | " return True # If we made it this far, no violation occurred and p might be prime.\n", 470 | "\n", 471 | "def is_prime(p, witnesses=50): # witnesses is a parameter with a default value.\n", 472 | " '''\n", 473 | " Tests whether a positive integer p is prime.\n", 474 | " For p < 2^64, the test is deterministic, using known good witnesses.\n", 475 | " Good witnesses come from a table at Wikipedia's article on the Miller-Rabin test,\n", 476 | " based on research by Pomerance, Selfridge and Wagstaff, Jaeschke, Jiang and Deng.\n", 477 | " For larger p, a number (by default, 50) of witnesses are chosen at random.\n", 478 | " '''\n", 479 | " if (p%2 == 0): # Might as well take care of even numbers at the outset!\n", 480 | " if p == 2:\n", 481 | " return True\n", 482 | " else:\n", 483 | " return False \n", 484 | " \n", 485 | " if p > 2**64: # We use the probabilistic test for large p.\n", 486 | " trial = 0\n", 487 | " while trial < witnesses:\n", 488 | " trial = trial + 1\n", 489 | " witness = randint(2,p-2) # A good range for possible witnesses\n", 490 | " if Miller_Rabin(p,witness) == False:\n", 491 | " return False\n", 492 | " return True\n", 493 | " \n", 494 | " else: # We use a determinisic test for p <= 2**64.\n", 495 | " verdict = Miller_Rabin(p,2)\n", 496 | " if p < 2047:\n", 497 | " return verdict # The witness 2 suffices.\n", 498 | " verdict = verdict and Miller_Rabin(p,3)\n", 499 | " if p < 1373653:\n", 500 | " return verdict # The witnesses 2 and 3 suffice.\n", 501 | " verdict = verdict and Miller_Rabin(p,5)\n", 502 | " if p < 25326001:\n", 503 | " return verdict # The witnesses 2,3,5 suffice.\n", 504 | " verdict = verdict and Miller_Rabin(p,7)\n", 505 | " if p < 3215031751:\n", 506 | " return verdict # The witnesses 2,3,5,7 suffice.\n", 507 | " verdict = verdict and Miller_Rabin(p,11)\n", 508 | " if p < 2152302898747:\n", 509 | " return verdict # The witnesses 2,3,5,7,11 suffice.\n", 510 | " verdict = verdict and Miller_Rabin(p,13)\n", 511 | " if p < 3474749660383:\n", 512 | " return verdict # The witnesses 2,3,5,7,11,13 suffice.\n", 513 | " verdict = verdict and Miller_Rabin(p,17)\n", 514 | " if p < 341550071728321:\n", 515 | " return verdict # The witnesses 2,3,5,7,11,17 suffice.\n", 516 | " verdict = verdict and Miller_Rabin(p,19) and Miller_Rabin(p,23)\n", 517 | " if p < 3825123056546413051:\n", 518 | " return verdict # The witnesses 2,3,5,7,11,17,19,23 suffice.\n", 519 | " verdict = verdict and Miller_Rabin(p,29) and Miller_Rabin(p,31) and Miller_Rabin(p,37)\n", 520 | " return verdict # The witnesses 2,3,5,7,11,17,19,23,29,31,37 suffice for testing up to 2^64. \n", 521 | " \n", 522 | "\n", 523 | "def random_prime(bitlength):\n", 524 | " while True:\n", 525 | " p = SystemRandom().getrandbits(bitlength) # A cryptographically secure random number.\n", 526 | " if is_prime(p):\n", 527 | " return p" 528 | ] 529 | }, 530 | { 531 | "cell_type": "code", 532 | "execution_count": null, 533 | "metadata": {}, 534 | "outputs": [], 535 | "source": [ 536 | "random_prime(100) # A random 100-bit prime" 537 | ] 538 | }, 539 | { 540 | "cell_type": "code", 541 | "execution_count": null, 542 | "metadata": {}, 543 | "outputs": [], 544 | "source": [ 545 | "random_prime(512) # A random 512-bit prime. Should be quick, thanks to Miller-Rabin!" 546 | ] 547 | }, 548 | { 549 | "cell_type": "code", 550 | "execution_count": null, 551 | "metadata": {}, 552 | "outputs": [], 553 | "source": [ 554 | "%timeit random_prime(1024) # Even 1024-bit primes should be quick!" 555 | ] 556 | }, 557 | { 558 | "cell_type": "code", 559 | "execution_count": null, 560 | "metadata": {}, 561 | "outputs": [], 562 | "source": [ 563 | "def RSA_privatekey(bitlength):\n", 564 | " '''\n", 565 | " Create private key for RSA, with given bitlength.\n", 566 | " Just a pair of big primes!\n", 567 | " '''\n", 568 | " p = random_prime(bitlength)\n", 569 | " q = random_prime(bitlength)\n", 570 | " return p,q # Returns both values, as a \"tuple\"" 571 | ] 572 | }, 573 | { 574 | "cell_type": "code", 575 | "execution_count": null, 576 | "metadata": {}, 577 | "outputs": [], 578 | "source": [ 579 | "type(RSA_privatekey(8)) # When a function returns multiple values, the type is \"tuple\"." 580 | ] 581 | }, 582 | { 583 | "cell_type": "code", 584 | "execution_count": null, 585 | "metadata": {}, 586 | "outputs": [], 587 | "source": [ 588 | "p,q = RSA_privatekey(512) # If a function outputs two values, you can assign them to two variables.\n", 589 | "print(\"Private key p = {}\".format(p))\n", 590 | "print(\"Private key q = {}\".format(q))" 591 | ] 592 | }, 593 | { 594 | "cell_type": "code", 595 | "execution_count": null, 596 | "metadata": {}, 597 | "outputs": [], 598 | "source": [ 599 | "def RSA_publickey(p,q, e = 65537):\n", 600 | " '''\n", 601 | " Makes the RSA public key out of \n", 602 | " two prime numbers p,q (the private key), \n", 603 | " and an auxiliary exponent e. \n", 604 | " By default, e = 65537.\n", 605 | " '''\n", 606 | " N = p*q\n", 607 | " return N,e" 608 | ] 609 | }, 610 | { 611 | "cell_type": "code", 612 | "execution_count": null, 613 | "metadata": {}, 614 | "outputs": [], 615 | "source": [ 616 | "N,e = RSA_publickey(p,q) # No value of e is input, so it will default to 65537\n", 617 | "\n", 618 | "print(\"Public key N = {}\".format(N)) # A big number!\n", 619 | "print(\"Public key e = {}\".format(e))" 620 | ] 621 | }, 622 | { 623 | "cell_type": "markdown", 624 | "metadata": {}, 625 | "source": [ 626 | "### Encryption and decryption\n", 627 | "\n", 628 | "Now we explain how the public key $(N,e)$ and the private key $(p,q)$ are used to encrypt and decrypt a (numerical) message $m$. If you wish to encrypt/decrypt a text message, one case use a numerical scheme like ASCII, of course. The message should be significantly shorter than the modulus, $m < N$ (ideally, shorter than the private key primes), but big enough so that $m^e$ is much bigger than $N$ (not usually a problem if $e = 65537$). \n", 629 | "\n", 630 | "The encryption procedure is simple -- it requires just one line of Python code, using the message and public key. The ciphertext $c$ is given by the formula\n", 631 | "$$c = m^e \\text{ mod } N,$$\n", 632 | "where here we mean the \"natural representative\" of $m^e$ modulo $N$. " 633 | ] 634 | }, 635 | { 636 | "cell_type": "code", 637 | "execution_count": null, 638 | "metadata": {}, 639 | "outputs": [], 640 | "source": [ 641 | "def RSA_encrypt(message, N, e):\n", 642 | " '''\n", 643 | " Encrypts message, using the public keys N,e.\n", 644 | " '''\n", 645 | " return pow(message, e, N)" 646 | ] 647 | }, 648 | { 649 | "cell_type": "code", 650 | "execution_count": null, 651 | "metadata": {}, 652 | "outputs": [], 653 | "source": [ 654 | "c = RSA_encrypt(17,N,e) # c is the ciphertext.\n", 655 | "print(\"The ciphertext is {}\".format(c)) # A very long number!" 656 | ] 657 | }, 658 | { 659 | "cell_type": "markdown", 660 | "metadata": {}, 661 | "source": [ 662 | "To decrypt the ciphertext, we need to \"undo\" the operation of raising to the $e$-th power modulo $N$. We must, effectively, take the $e$-th root of the ciphertext, modulo $N$. This is what we studied earlier in this notebook. Namely, if $c \\equiv m^e \\text{ mod } N$ is the ciphertext, and $ef \\equiv 1$ modulo $\\phi(N)$, then\n", 663 | "$$c^f \\equiv m^{ef} \\equiv m \\text{ mod } N.$$\n", 664 | "\n", 665 | "So we must raise the ciphertext to the $f$ power, where $f$ is the multiplicative inverse of $e$ modulo $\\phi(N)$. Given a giant number $N$, it is difficult to compute the totient $\\phi(N)$. But, with the **private key** $p$ and $q$ (primes), the fact that $N = pq$ implies\n", 666 | "$$\\phi(N) = (p-1) \\cdot (q-1) = pq - p - q + 1 = N - p - q + 1.$$\n", 667 | "\n", 668 | "Armed with the private key (and the public key, which everyone has), we can decrypt a message in just a few lines of Python code." 669 | ] 670 | }, 671 | { 672 | "cell_type": "code", 673 | "execution_count": null, 674 | "metadata": {}, 675 | "outputs": [], 676 | "source": [ 677 | "def RSA_decrypt(ciphertext, p,q,N,e):\n", 678 | " '''\n", 679 | " Decrypts message, using the private key (p,q) \n", 680 | " and the public key (N,e). We allow the public key N as\n", 681 | " an input parameter, to avoid recomputing it.\n", 682 | " '''\n", 683 | " tot = N - (p+q) + 1\n", 684 | " f = mult_inverse(e,tot) # This uses the Euclidean algorithm... very quick!\n", 685 | " return pow(ciphertext,f,N)" 686 | ] 687 | }, 688 | { 689 | "cell_type": "code", 690 | "execution_count": null, 691 | "metadata": {}, 692 | "outputs": [], 693 | "source": [ 694 | "RSA_decrypt(c,p,q,N,e) # We decrypt the ciphertext... what is the result?" 695 | ] 696 | }, 697 | { 698 | "cell_type": "markdown", 699 | "metadata": {}, 700 | "source": [ 701 | "That's the entire process of encryption and decryption. Encryption requires just the public key $(N,e)$ and decryption requires the private key $(p,q)$ too. Everything else is modular arithmetic, using Euler's theorem and the Euclidean algorithm to find modular multiplicative inverses.\n", 702 | "\n", 703 | "From a practical standpoint, there are many challenges, and we just mention a few here.\n", 704 | "\n", 705 | "**Key generation:** The person who constructs the private key $(p,q)$ needs to be careful. The primes $p$ and $q$ need to be pretty large (512 bits, or 1024 bits perhaps), which is not so difficult. They also need to be constructed **randomly**. For imagine that Alice comes up with her private key $(p,q)$ and Anne comes up with her private key $(q,r)$, with the same prime $q$ in common. Their public keys will include the numbers $N = pq$ and $M = qr$. If someone like Arjen comes along and starts taking GCDs of all the public keys in a database, that person will stumble upon the fact that $GCD(N,M) = q$, from which the private keys $(p,q)$ and $(q,r)$ can be derived. And this sort of disaster has happened! Poorly generated keys were stored in a database, and [discovered by Arjen Lenstra et al.](https://eprint.iacr.org/2012/064.pdf).\n", 706 | "\n", 707 | "**Security by difficulty of factoring:** The security of RSA is based on the difficulty of obtaining the private key $(p,q)$ from the public key $(N,e)$. Since $N = pq$, this is precisely the difficulty of factoring a large number $N$ into two primes (given the knowledge that it is the product of two primes). Currently it seems very difficult to factor large numbers. The RSA factoring challenges give monetary rewards for factoring such large $N$. The record (2017) is factoring a [768-bit (232 digit) number, RSA-768](https://en.wikipedia.org/wiki/RSA_numbers#RSA-768). For this reason, we may consider a 1024-bit number secure for now (i.e. $p$ and $q$ are 512-bit primes), or use a 2048-bit number if we are paranoid. If quantum computers develop sufficiently, they could make factoring large numbers easy, and RSA will have to be replaced by a quantum-secure protocol. \n", 708 | "\n", 709 | "**Web of Trust:** Trust needs to begin somewhere. Every time Alice and Bob communicate, Alice should not come up with a new private key, and give Bob the new public key. For if they are far apart, how does Bob know he's receiving Alice's public key and not talking to an eavesdropper Eve? Instead, it is better for Alice to register (in person, perhaps) her public key at some time. She can create her private key $(p,q)$ and register the resulting public key $(N,e)$ with some \"key authority\" who checks her identity at the time. The key authority then stores everyone's public keys -- effectively they say \"if you want to send a secure message to Alice, use the following public key: (..., ...)\" Then Bob can consult the key authority when he wishes to communicate securely to Alice, and this private/public key combination can be used for years.\n", 710 | "\n", 711 | "But, as one might guess, this kicks the trust question to another layer. How does Bob know he's communicating with the key authority? The key authorities need to have their own authentication mechanism, etc.. One way to avoid going down a rabbithole of mistrust is to *distribute* trust across a network of persons. Instead of a centralized \"key authority\", one can distribute one's public keys across an entire network of communicators (read about [openPGP](https://en.wikipedia.org/wiki/Pretty_Good_Privacy#OpenPGP)). Then Bob, if he wishes, can double-check Alice's public keys against the records of numerous members of the network -- assuming that hackers haven't gotten to all of them! \n", 712 | "\n", 713 | "In practice, some implementations of RSA use a more centralized authority and others rely on a web of trust. Cryptography requires a clever application of modular arithmetic (in Diffie-Hellman, RSA, and many other systems), but also a meticulous approach to implementation. Often the challenges of implementation introduce new problems in number theory." 714 | ] 715 | }, 716 | { 717 | "cell_type": "markdown", 718 | "metadata": {}, 719 | "source": [ 720 | "### Digital signatures\n", 721 | "\n", 722 | "A variant of RSA is used to \"digitally sign\" a document. Not worrying about keeping a message private for now, suppose that Alice wants to send Bob a message and **sign** the message in such a way that Bob can be confident it was sent by Alice. \n", 723 | "\n", 724 | "Alice can digitally sign her message by first **hashing** the message and then encrypting the hash using her **private key** (previously the *public key* was used for encryption -- this is different!). Hashing a message is an irreversible process that turns a message of possibly long length into a nonsense-message of typically fixed length, in such a way that the original message cannot be recovered from the nonsense-message. \n", 725 | "\n", 726 | "There is a science to secure hashing, which we don't touch on here. Instead, we import the `sha512` hashing function from the Python standard package `hashlib`. The input to `sha512` is a string of arbitrary length, and the output is a sequence of 512 bits. Here in Python 3, we also must specify the Unicode encoding (`utf-8`) for the string to be hashed. One can convert the 512 bits of hash into 64 bytes (512/8 = 64) which can be viewed as a 64-character string via ASCII. This 64-byte string is called the *digest* of the hash. It's all very biological. Note that many of the characters won't display very nicely, since they are out of the code range 32-126!" 727 | ] 728 | }, 729 | { 730 | "cell_type": "code", 731 | "execution_count": null, 732 | "metadata": {}, 733 | "outputs": [], 734 | "source": [ 735 | "from hashlib import sha512\n", 736 | "\n", 737 | "print(sha512(\"I like sweet potato hash.\".encode('utf-8')).digest()) # A 64-character string of hash." 738 | ] 739 | }, 740 | { 741 | "cell_type": "markdown", 742 | "metadata": {}, 743 | "source": [ 744 | "Hashes are designed to be irreversible. Nobody should be able to reverse the hashing process and recover the original string ('I like sweet potato hash') from the output of sha512. Moreover, hashes should avoid collisions -- although different input strings *can* yield the same hashed result, such \"collisions\" should be exceedingly rare in practice. You can read more about [SHA-512 and others at Wikipedia](https://en.wikipedia.org/wiki/SHA-2).\n", 745 | "\n", 746 | "Now, if Alice wishes to sign a message `m`, and send it to Bob, she goes through the following steps (in the RSA signature protocol).\n", 747 | "\n", 748 | "1. Alice hashes her message using a method such as SHA-512. Let `h` be the resulting hash.\n", 749 | "\n", 750 | "2. Alice **encrypts** the hash by computing $s = h^f$ modulo $N$. Here $f$ is the multiplicative inverse of $e$ modulo $\\phi(N)$, just as it was in RSA encryption. Note that this step requires knowledge of the private key $(p,q)$ to compute $\\phi(N)$ to compute $f$. Hence only Alice can encrypt the has in this way.\n", 751 | "\n", 752 | "3. Alice sends this encrypted hash along with her message to Bob, along with a note that she signed it using SHA-512 and her RSA key (without revealing her private keys, of course!).\n", 753 | "\n", 754 | "When Bob receives the (plaintext) message $m$ and signature $s$, he carries out the following authentication process.\n", 755 | "\n", 756 | "1. Bob computes $s^e$ modulo $N$. Since $s^e = h^{fe} = h$ modulo $N$, Bob now has the hash of the message $h$. \n", 757 | "\n", 758 | "2. Bob also computes the SHA-512 hash of the received message $m$, and compares it to the has he computed in step 1. If they match, then Alice indeed signed the message he received.\n", 759 | "\n", 760 | "We leave implementation of this process to the exercises." 761 | ] 762 | }, 763 | { 764 | "cell_type": "markdown", 765 | "metadata": {}, 766 | "source": [ 767 | "### Exercises\n", 768 | "\n", 769 | "1. Why might the exponent $e = 65537$ be a computationally convenient choice? Consider Pingala's algorithm.\n", 770 | "\n", 771 | "2. What would happen if the message $m$ encrypted by RSA were *equal* to one of these primes of the private key? How might such an occurrence be avoided, and is this something to be concerned about in practice?\n", 772 | "\n", 773 | "3. Look at the technical document [on OpenPGP](https://tools.ietf.org/html/rfc4880), and try to figure out how RSA and/or other cryptosystems are being used and implemented in practice. Write a 1-2 paragraph nontechnical summary of your findings.\n", 774 | "\n", 775 | "4. Suppose that you choose $M$ prime numbers at random between $2^{b-1}$ and $2^{b}$. Assuming that prime numbers near $x$ have a density $1 / \\log(x)$, estimate the probability that there is a \"collision\" -- that at least two of the $M$ prime numbers are the same. What is this probability when $b = 512$ and $M$ is two billion? (E.g., if a billion people use a pair of 512-bit private keys). Look up the \"Birthday Problem\" for some hints if you haven't seen this before.\n", 776 | "\n", 777 | "5. Create a function `sign(message, p,q,N,e)` to carry out the RSA signature protocol described above, based on a private key $(p,q)$ with public key $(N,e)$. Create a function `verify(message, signature, N, e)` to verify a signed message. Use the SHA-512 algorithm throughout, and check that your functions work.\n", 778 | "\n" 779 | ] 780 | }, 781 | { 782 | "cell_type": "code", 783 | "execution_count": null, 784 | "metadata": {}, 785 | "outputs": [], 786 | "source": [] 787 | } 788 | ], 789 | "metadata": { 790 | "kernelspec": { 791 | "display_name": "Python 3", 792 | "language": "python", 793 | "name": "python3" 794 | }, 795 | "language_info": { 796 | "codemirror_mode": { 797 | "name": "ipython", 798 | "version": 3 799 | }, 800 | "file_extension": ".py", 801 | "mimetype": "text/x-python", 802 | "name": "python", 803 | "nbconvert_exporter": "python", 804 | "pygments_lexer": "ipython3", 805 | "version": "3.6.4" 806 | } 807 | }, 808 | "nbformat": 4, 809 | "nbformat_minor": 1 810 | } 811 | -------------------------------------------------------------------------------- /PwNT Notebook 7.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Part 7: The RSA Cryptosystem" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "In the previous notebook, we studied a few basic ciphers together with Diffie-Hellman key exchange. The Vigenère cipher we studied uses a **secret key** for encrypting and decrypting messages. The same key is used for both encryption and decryption, so we say it is a **symmetric key** cipher. In order for two parties to share the same secret key, we studied the Diffie-Hellman protocol, whose security rests on the difficulty of the discrete logarithm problem.\n", 15 | "\n", 16 | "Although this represents progress towards secure communication, it is particularly vulnerable to problems of authentication. For example, imagine a \"man-in-the-middle attack\": Alice and Bob wish to communicate securely, and begin the Diffie-Hellman protocol over an insecure line. But **Eve** has intercepted the line. To Alice, she pretends to be Bob, and to Bob, she pretends to be Alice. She goes through the Diffie-Hellman protocol with each, obtaining two secret keys, and decrypting/encrypting messages as they pass through her computer. In this way, Alice and Bob think they are talking to each other, but Eve is just passing (and understanding) their messages the whole time!\n", 17 | "\n", 18 | "To thwart such an attack, we need some type of authentication. We need something **asymmetric** -- something one person can do that no other person can do, like a verifiable signature, so that we can be sure we're communicating with the intended person. For such a purpose, we introduce the RSA cryptosystem. Computationally based on modular exponentiation, its security rests on the difficulty of factoring large numbers.\n", 19 | "\n", 20 | "The material in this notebook complements Chapter 7 of [An Illustrated Theory of Numbers](http://illustratedtheoryofnumbers.com/index.html)." 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "## Table of Contents\n", 28 | "\n", 29 | "- [Euler's theorem and modular roots](#euler)\n", 30 | "- [The RSA protocol](#RSA)" 31 | ] 32 | }, 33 | { 34 | "cell_type": "markdown", 35 | "metadata": {}, 36 | "source": [ 37 | "" 38 | ] 39 | }, 40 | { 41 | "cell_type": "markdown", 42 | "metadata": {}, 43 | "source": [ 44 | "## Euler's Theorem and Modular Roots\n", 45 | "\n", 46 | "Recall Fermat's Little Theorem: if $p$ is prime and $GCD(a,p) = 1$, then $a^{p-1} \\equiv 1$ mod $p$. This is a special case of Euler's theorem, which holds for any modulus $m$.\n", 47 | "\n", 48 | "### Euler's theorem and the totient\n", 49 | "\n", 50 | "Euler's theorem states: if $m$ is a positive integer and $GCD(a,m) = 1$, then $a^{\\phi(m)} \\equiv 1$ mod $m$. Here $\\phi(m)$ denotes the **totient** of $m$, which is the number of elements of $\\{ 1,...,m \\}$ which are coprime to $m$. We give a brute force implementation of the totient first, using our old Euclidean algorithm code for the GCD." 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": { 57 | "collapsed": true 58 | }, 59 | "outputs": [], 60 | "source": [ 61 | "def GCD(a,b):\n", 62 | " while b: # Recall that != means \"not equal to\".\n", 63 | " a, b = b, a % b\n", 64 | " return abs(a)\n", 65 | "\n", 66 | "def totient(m):\n", 67 | " tot = 0 # The running total.\n", 68 | " j = 0\n", 69 | " while j < m: # We go up to m, because the totient of 1 is 1 by convention.\n", 70 | " j = j + 1 # Last step of while loop: j = m-1, and then j = j+1, so j = m.\n", 71 | " if GCD(j,m) == 1:\n", 72 | " tot = tot + 1\n", 73 | " return tot" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": null, 79 | "metadata": { 80 | "collapsed": false 81 | }, 82 | "outputs": [], 83 | "source": [ 84 | "totient(17) # The totient of a prime p should be p-1." 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": null, 90 | "metadata": { 91 | "collapsed": false 92 | }, 93 | "outputs": [], 94 | "source": [ 95 | "totient(1000)" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "metadata": { 102 | "collapsed": false 103 | }, 104 | "outputs": [], 105 | "source": [ 106 | "totient(1) # Check a borderline case, to make sure we didn't make an off-by-one error." 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": null, 112 | "metadata": { 113 | "collapsed": false 114 | }, 115 | "outputs": [], 116 | "source": [ 117 | "17**totient(1000) % 1000 # Let's demonstrate Euler's theorem. Note GCD(17,1000) = 1." 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": null, 123 | "metadata": { 124 | "collapsed": false 125 | }, 126 | "outputs": [], 127 | "source": [ 128 | "pow(17,totient(1000),1000) # A more efficient version, using the pow command." 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": null, 134 | "metadata": { 135 | "collapsed": false 136 | }, 137 | "outputs": [], 138 | "source": [ 139 | "%timeit totient(123456)" 140 | ] 141 | }, 142 | { 143 | "cell_type": "markdown", 144 | "metadata": {}, 145 | "source": [ 146 | "The totient is a **multiplicative function**, meaning that if $GCD(a,b) = 1$, then $\\phi(ab) = \\phi(a) \\phi(b)$. Therefore, the totient of number can be found quickly from the totient of the prime powers within its decomposition. We can re-implement the totient using our functions for prime decomposition and multiplicative functions from [Notebook 4](http://illustratedtheoryofnumbers.com/prog.html#notebooks)." 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "execution_count": null, 152 | "metadata": { 153 | "collapsed": true 154 | }, 155 | "outputs": [], 156 | "source": [ 157 | "from math import sqrt # We'll want to use the square root.\n", 158 | "\n", 159 | "def smallest_factor(n):\n", 160 | " '''\n", 161 | " Gives the smallest prime factor of n.\n", 162 | " '''\n", 163 | " if n < 2:\n", 164 | " return None # No prime factors!\n", 165 | " \n", 166 | " test_factor = 2 # The smallest possible prime factor.\n", 167 | " max_factor = sqrt(n) # we don't have to search past sqrt(n).\n", 168 | " \n", 169 | " while test_factor <= max_factor:\n", 170 | " if n%test_factor == 0:\n", 171 | " return test_factor\n", 172 | " test_factor = test_factor + 1 # This could be sped up.\n", 173 | " \n", 174 | " return n # If we didn't find a factor up to sqrt(n), n itself is prime!\n", 175 | "\n", 176 | "def decompose(N):\n", 177 | " '''\n", 178 | " Gives the unique prime decomposition of a positive integer N,\n", 179 | " as a dictionary with primes as keys and exponents as values.\n", 180 | " '''\n", 181 | " current_number = N # We'll divide out factors from current_number until we get 1.\n", 182 | " decomp = {} # An empty dictionary to start.\n", 183 | " while current_number > 1:\n", 184 | " p = smallest_factor(current_number) # The smallest prime factor of the current number.\n", 185 | " if p in decomp.keys(): # Is p already in the list of keys?\n", 186 | " decomp[p] = decomp[p] + 1 # Increase the exponent (value with key p) by 1.\n", 187 | " else: # \"else\" here means \"if p is not in decomp.keys()\".\n", 188 | " decomp[p] = 1 # Creates a new entry in the dictionary, with key p and value 1.\n", 189 | " current_number = current_number / p # Factor out p.\n", 190 | " return decomp\n", 191 | "\n", 192 | "def mult_function(f_pp):\n", 193 | " '''\n", 194 | " When a function f_pp(p,e) of two arguments is input,\n", 195 | " this outputs a multiplicative function obtained from f_pp\n", 196 | " via prime decomposition.\n", 197 | " '''\n", 198 | " def f(n):\n", 199 | " D = decompose(n)\n", 200 | " result = 1\n", 201 | " for p in D:\n", 202 | " result = result * f_pp(p, D[p])\n", 203 | " return result\n", 204 | " \n", 205 | " return f" 206 | ] 207 | }, 208 | { 209 | "cell_type": "markdown", 210 | "metadata": {}, 211 | "source": [ 212 | "When $p^e$ is a prime power, the numbers among $1, \\ldots, p^e$ are coprime to $p^e$ precisely when they are **not** multiples of $p$. Therefore, the totient of a prime power is pretty easy to compute:\n", 213 | "$$\\phi(p^e) = p^e - p^{e-1} = p^{e-1} (p-1).$$\n", 214 | "We implement this, and use the multiplicative function code to complete the implementation of the totient." 215 | ] 216 | }, 217 | { 218 | "cell_type": "code", 219 | "execution_count": null, 220 | "metadata": { 221 | "collapsed": true 222 | }, 223 | "outputs": [], 224 | "source": [ 225 | "def totient_pp(p,e):\n", 226 | " return (p**(e-1)) * (p-1)" 227 | ] 228 | }, 229 | { 230 | "cell_type": "markdown", 231 | "metadata": {}, 232 | "source": [ 233 | "Note that for efficiency, the computation of $p^{e-1}(p-1)$ is probably faster than the computation of $p^e - p^{e-1}$ (which relies on two exponents)." 234 | ] 235 | }, 236 | { 237 | "cell_type": "code", 238 | "execution_count": null, 239 | "metadata": { 240 | "collapsed": true 241 | }, 242 | "outputs": [], 243 | "source": [ 244 | "totient = mult_function(totient_pp)" 245 | ] 246 | }, 247 | { 248 | "cell_type": "code", 249 | "execution_count": null, 250 | "metadata": { 251 | "collapsed": false 252 | }, 253 | "outputs": [], 254 | "source": [ 255 | "totient(1000)" 256 | ] 257 | }, 258 | { 259 | "cell_type": "code", 260 | "execution_count": null, 261 | "metadata": { 262 | "collapsed": false 263 | }, 264 | "outputs": [], 265 | "source": [ 266 | "%timeit totient(123456)" 267 | ] 268 | }, 269 | { 270 | "cell_type": "markdown", 271 | "metadata": {}, 272 | "source": [ 273 | "This should be **much** faster than the previous brute-force computation of the totient." 274 | ] 275 | }, 276 | { 277 | "cell_type": "markdown", 278 | "metadata": {}, 279 | "source": [ 280 | "### Modular roots" 281 | ] 282 | }, 283 | { 284 | "cell_type": "markdown", 285 | "metadata": {}, 286 | "source": [ 287 | "A consequence of Euler's theorem is that -- depending on the modulus -- some exponentiation can be \"reversed\" by another exponentiation, a form of taking a \"root\" in modular arithmetic. For example, if we work modulo $100$, and $GCD(a,100) = 1$, then Euler's theorem states that\n", 288 | "$$a^{40} \\equiv 1 \\text{ mod } 100.$$\n", 289 | "It follows that $a^{80} \\equiv 1$ and $a^{81} \\equiv a$, modulo $100$. Expanding this, we find\n", 290 | "$$a \\equiv a^{81} = a^{3 \\cdot 27} = (a^3)^{27} \\text{ mod } 100.$$\n", 291 | "\n", 292 | "What all this computation shows is that \"raising to the 27th power\" is like \"taking the cube root\", modulo 100 (and with appropriate bases)." 293 | ] 294 | }, 295 | { 296 | "cell_type": "code", 297 | "execution_count": null, 298 | "metadata": { 299 | "collapsed": false 300 | }, 301 | "outputs": [], 302 | "source": [ 303 | "for b in range(20):\n", 304 | " b_cubed = pow(b,3,100)\n", 305 | " bb = pow(b_cubed,27,100)\n", 306 | " print b, b_cubed, bb, GCD(b,100) == 1" 307 | ] 308 | }, 309 | { 310 | "cell_type": "markdown", 311 | "metadata": {}, 312 | "source": [ 313 | "In every line ending with `True`, the first and third numbers should match. This will happen in some `False` lines too, but not reliably since Euler's theorem does not apply there.\n", 314 | "\n", 315 | "We found the exponent 27 -- reversing the cubing operation -- by an ad hoc sort of procedure. The relationship between 27 and 3, which made things work, is that\n", 316 | "$$3 \\cdot 27 \\equiv 1 \\text{ mod } 40.$$\n", 317 | "In other words, $3 \\cdot 27 = 1 + 40k$ for some (positive, in fact) integer $k$.\n", 318 | "\n", 319 | "Recalling that $40 = \\phi(100)$, this relationship and Euler's theorem imply that\n", 320 | "$$a^{3 \\cdot 27} = a^{1 + 40k} \\equiv a^1 = a \\text{ mod } 100.$$\n", 321 | "\n", 322 | "By this argument, we have the following consequence of Euler's theorem. If $GCD(a,m) = 1$, and $ef \\equiv 1$ mod $\\phi(m)$, then\n", 323 | "$$a^{ef} \\equiv a \\text{ mod } \\phi(m).$$\n", 324 | "In this way, \"raising to the $f$ power\" is like \"taking the $e$-th root\", modulo $m$. \n", 325 | "\n", 326 | "If we are given $f$, then $e$ is a **multiplicative inverse** of $f$ modulo $\\phi(m)$. In particular, such a multiplicative inverse exists if and only if $GCD(e,\\phi(m)) = 1$. The following function computes a multiplicative inverse, by adapting the `solve_LDE` function from [Notebook 2](). After all, solving $ex \\equiv 1$ mod $m$ is equivalent to solving the linear Diophantine equation $ex + my = 1$ (and only caring about the $x$-value). \n" 327 | ] 328 | }, 329 | { 330 | "cell_type": "code", 331 | "execution_count": null, 332 | "metadata": { 333 | "collapsed": true 334 | }, 335 | "outputs": [], 336 | "source": [ 337 | "def mult_inverse(a,m):\n", 338 | " '''\n", 339 | " Finds the multiplicative inverse of a, mod m.\n", 340 | " If GCD(a,m) = 1, this is returned via its natural representative.\n", 341 | " Otherwise, None is returned.\n", 342 | " ''' \n", 343 | " u = a # We use u instead of dividend.\n", 344 | " v = m # We use v instead of divisor.\n", 345 | " u_hops, u_skips = 1,0 # u is built from one hop (a) and no skips.\n", 346 | " v_hops, v_skips = 0,1 # v is built from no hops and one skip (b).\n", 347 | " while v != 0: # We could just write while v:\n", 348 | " q = u // v # q stands for quotient.\n", 349 | " r = u % v # r stands for remainder. So u = q(v) + r.\n", 350 | " \n", 351 | " r_hops = u_hops - q * v_hops # Tally hops\n", 352 | " r_skips = u_skips - q * v_skips # Tally skips\n", 353 | " \n", 354 | " u,v = v,r # The new dividend,divisor is the old divisor,remainder.\n", 355 | " u_hops, v_hops = v_hops, r_hops # The new u_hops, v_hops is the old v_hops, r_hops\n", 356 | " u_skips, v_skips = v_skips, r_skips # The new u_skips, v_skips is the old v_skips, r_skips\n", 357 | " \n", 358 | " g = u # The variable g now describes the GCD of a and b.\n", 359 | " if g == 1:\n", 360 | " return u_hops % m\n", 361 | " else: # When GCD(a,m) is not 1...\n", 362 | " return None" 363 | ] 364 | }, 365 | { 366 | "cell_type": "code", 367 | "execution_count": null, 368 | "metadata": { 369 | "collapsed": false 370 | }, 371 | "outputs": [], 372 | "source": [ 373 | "mult_inverse(3,40) # 3 times what is congruent to 1, mod 40?" 374 | ] 375 | }, 376 | { 377 | "cell_type": "code", 378 | "execution_count": null, 379 | "metadata": { 380 | "collapsed": true 381 | }, 382 | "outputs": [], 383 | "source": [ 384 | "mult_inverse(5,40) # None should be returned." 385 | ] 386 | }, 387 | { 388 | "cell_type": "markdown", 389 | "metadata": {}, 390 | "source": [ 391 | "Let's test this out on some bigger numbers." 392 | ] 393 | }, 394 | { 395 | "cell_type": "code", 396 | "execution_count": null, 397 | "metadata": { 398 | "collapsed": false 399 | }, 400 | "outputs": [], 401 | "source": [ 402 | "from random import randint\n", 403 | "while True:\n", 404 | " m = randint(1000000, 9999999) # a random 7-digit number\n", 405 | " e = randint(100,999) # a random 3-digit number\n", 406 | " a = randint(10,99) # a random 2-digit number\n", 407 | " if GCD(a,m) == 1:\n", 408 | " tot = totient(m)\n", 409 | " if GCD(e,tot) == 1:\n", 410 | " f = mult_inverse(e,tot)\n", 411 | " test_number = pow(a, e*f, m)\n", 412 | " print \"Success!\"\n", 413 | " print \"%d ^ (%d * %d) = %d, mod %d\"%(a,e,f,test_number,m)\n", 414 | " break # Escapes the loop once an example is found!" 415 | ] 416 | }, 417 | { 418 | "cell_type": "markdown", 419 | "metadata": {}, 420 | "source": [ 421 | "### Exercises\n", 422 | "\n", 423 | "1. What is the largest integer whose totient is 100? Study this by a brute force search, i.e., looping through the integers up to 10000\n", 424 | "\n", 425 | "2. For which integers $n$ is it true that $\\phi(n) = n/2$? Study this by a brute force search in order to make a conjecture. Then prove it if you can.\n", 426 | "\n", 427 | "3. Compute the totient of the numbers from 1 to 10000, and analyze the results. The totient $\\phi(n)$ is always less than $n$ when $n > 1$, but how does the ratio $\\phi(n) / n$ behave? Create a graph. What is the average value of the ratio? \n", 428 | "\n", 429 | "4. If $a^{323} \\equiv 802931$, mod $5342481$, and $GCD(a, 5342481) = 1$, and $0 < a < 5342481$, then what is $a$? \n", 430 | "\n", 431 | "5. Challenge: Create a function `superpow(x,y,z,m)` which computes $x^{y^z}$ modulo $m$ efficiently, when $GCD(x,m) = 1$ and $m$ is small enough to factor." 432 | ] 433 | }, 434 | { 435 | "cell_type": "markdown", 436 | "metadata": {}, 437 | "source": [ 438 | "" 439 | ] 440 | }, 441 | { 442 | "cell_type": "markdown", 443 | "metadata": {}, 444 | "source": [ 445 | "## The RSA protocol" 446 | ] 447 | }, 448 | { 449 | "cell_type": "markdown", 450 | "metadata": {}, 451 | "source": [ 452 | "Like Diffie-Hellman, the RSA protocol involves a series of computations in modular arithmetic, taking care to keep some numbers private while making others public. RSA was published two years after Diffie-Hellman, in 1978 by Rivest, Shamir, and Adelman (hence its name). The great advance of the RSA protocol was its **asymmetry**. While Diffie-Hellman is used for symmetric key cryptography (using the same key to encrypt and decrypt), the RSA protocol has two keys: a **public key** that can be used by anyone for encryption and a **private key** that can be used by its owner for decryption. \n", 453 | "\n", 454 | "In this way, if Alice publishes her public key online, anyone can send her an encrypted message. But as long as she keeps her private key private, **only** Alice can decrypt the messages sent to her. Such an asymmetry allows RSA to be used for authentication -- if the owner of a private key has an ability nobody else has, then this ability can be used to prove the owner's identity. In practice, this is one of the most common applications of RSA, guaranteeing that we are communicating with the intended person." 455 | ] 456 | }, 457 | { 458 | "cell_type": "markdown", 459 | "metadata": {}, 460 | "source": [ 461 | "In the RSA protocol, the **private key** is a pair of large (e.g. 512 bit) prime numbers, called $p$ and $q$. The **public key** is the pair $(N, e)$, where $N$ is defined to be the product $N = pq$ and $e$ is an auxiliary number called the exponent. The number $e$ is often (for computational efficiency and other reasons) taken to be 65537 -- the same number $e$ can be used over and over by different people. But it is absolutely crucial that the same private keys $p$ and $q$ are not used by different individuals. Individuals must create and safely keep their own private key." 462 | ] 463 | }, 464 | { 465 | "cell_type": "markdown", 466 | "metadata": {}, 467 | "source": [ 468 | "We begin with the creation of a private key $(p,q)$. We use the `SystemRandom` function (see the previous Python Notebook) to cook up cryptographically secure random numbers, and the Miller-Rabin test to certify primality." 469 | ] 470 | }, 471 | { 472 | "cell_type": "code", 473 | "execution_count": null, 474 | "metadata": { 475 | "collapsed": true 476 | }, 477 | "outputs": [], 478 | "source": [ 479 | "from random import SystemRandom, randint\n", 480 | "\n", 481 | "def Miller_Rabin(p, base):\n", 482 | " '''\n", 483 | " Tests whether p is prime, using the given base.\n", 484 | " The result False implies that p is definitely not prime.\n", 485 | " The result True implies that p **might** be prime.\n", 486 | " It is not a perfect test!\n", 487 | " '''\n", 488 | " result = 1\n", 489 | " exponent = p-1\n", 490 | " modulus = p\n", 491 | " bitstring = bin(exponent)[2:] # Chop off the '0b' part of the binary expansion of exponent\n", 492 | " for bit in bitstring: # Iterates through the \"letters\" of the string. Here the letters are '0' or '1'.\n", 493 | " sq_result = result*result % modulus # We need to compute this in any case.\n", 494 | " if sq_result == 1:\n", 495 | " if (result != 1) and (result != exponent): # Note that exponent is congruent to -1, mod p.\n", 496 | " return False # a ROO violation occurred, so p is not prime\n", 497 | " if bit == '0':\n", 498 | " result = sq_result \n", 499 | " if bit == '1':\n", 500 | " result = (sq_result * base) % modulus\n", 501 | " if result != 1:\n", 502 | " return False # a FLT violation occurred, so p is not prime.\n", 503 | " \n", 504 | " return True # If we made it this far, no violation occurred and p might be prime.\n", 505 | "\n", 506 | "def is_prime(p, witnesses=50): # witnesses is a parameter with a default value.\n", 507 | " '''\n", 508 | " Tests whether a positive integer p is prime.\n", 509 | " For p < 2^64, the test is deterministic, using known good witnesses.\n", 510 | " Good witnesses come from a table at Wikipedia's article on the Miller-Rabin test,\n", 511 | " based on research by Pomerance, Selfridge and Wagstaff, Jaeschke, Jiang and Deng.\n", 512 | " For larger p, a number (by default, 50) of witnesses are chosen at random.\n", 513 | " '''\n", 514 | " if (p%2 == 0): # Might as well take care of even numbers at the outset!\n", 515 | " if p == 2:\n", 516 | " return True\n", 517 | " else:\n", 518 | " return False \n", 519 | " \n", 520 | " if p > 2**64: # We use the probabilistic test for large p.\n", 521 | " trial = 0\n", 522 | " while trial < witnesses:\n", 523 | " trial = trial + 1\n", 524 | " witness = randint(2,p-2) # A good range for possible witnesses\n", 525 | " if Miller_Rabin(p,witness) == False:\n", 526 | " return False\n", 527 | " return True\n", 528 | " \n", 529 | " else: # We use a determinisic test for p <= 2**64.\n", 530 | " verdict = Miller_Rabin(p,2)\n", 531 | " if p < 2047:\n", 532 | " return verdict # The witness 2 suffices.\n", 533 | " verdict = verdict and Miller_Rabin(p,3)\n", 534 | " if p < 1373653:\n", 535 | " return verdict # The witnesses 2 and 3 suffice.\n", 536 | " verdict = verdict and Miller_Rabin(p,5)\n", 537 | " if p < 25326001:\n", 538 | " return verdict # The witnesses 2,3,5 suffice.\n", 539 | " verdict = verdict and Miller_Rabin(p,7)\n", 540 | " if p < 3215031751:\n", 541 | " return verdict # The witnesses 2,3,5,7 suffice.\n", 542 | " verdict = verdict and Miller_Rabin(p,11)\n", 543 | " if p < 2152302898747:\n", 544 | " return verdict # The witnesses 2,3,5,7,11 suffice.\n", 545 | " verdict = verdict and Miller_Rabin(p,13)\n", 546 | " if p < 3474749660383:\n", 547 | " return verdict # The witnesses 2,3,5,7,11,13 suffice.\n", 548 | " verdict = verdict and Miller_Rabin(p,17)\n", 549 | " if p < 341550071728321:\n", 550 | " return verdict # The witnesses 2,3,5,7,11,17 suffice.\n", 551 | " verdict = verdict and Miller_Rabin(p,19) and Miller_Rabin(p,23)\n", 552 | " if p < 3825123056546413051:\n", 553 | " return verdict # The witnesses 2,3,5,7,11,17,19,23 suffice.\n", 554 | " verdict = verdict and Miller_Rabin(p,29) and Miller_Rabin(p,31) and Miller_Rabin(p,37)\n", 555 | " return verdict # The witnesses 2,3,5,7,11,17,19,23,29,31,37 suffice for testing up to 2^64. \n", 556 | " \n", 557 | "\n", 558 | "def random_prime(bitlength):\n", 559 | " while True:\n", 560 | " p = SystemRandom().getrandbits(bitlength) # A cryptographically secure random number.\n", 561 | " if is_prime(p):\n", 562 | " return p" 563 | ] 564 | }, 565 | { 566 | "cell_type": "code", 567 | "execution_count": null, 568 | "metadata": { 569 | "collapsed": false 570 | }, 571 | "outputs": [], 572 | "source": [ 573 | "random_prime(100) # A random 100-bit prime" 574 | ] 575 | }, 576 | { 577 | "cell_type": "code", 578 | "execution_count": null, 579 | "metadata": { 580 | "collapsed": false 581 | }, 582 | "outputs": [], 583 | "source": [ 584 | "random_prime(512) # A random 512-bit prime. Should be quick, thanks to Miller-Rabin!" 585 | ] 586 | }, 587 | { 588 | "cell_type": "code", 589 | "execution_count": null, 590 | "metadata": { 591 | "collapsed": false 592 | }, 593 | "outputs": [], 594 | "source": [ 595 | "%timeit random_prime(1024) # Even 1024-bit primes should be quick!" 596 | ] 597 | }, 598 | { 599 | "cell_type": "code", 600 | "execution_count": null, 601 | "metadata": { 602 | "collapsed": true 603 | }, 604 | "outputs": [], 605 | "source": [ 606 | "def RSA_privatekey(bitlength):\n", 607 | " '''\n", 608 | " Create private key for RSA, with given bitlength.\n", 609 | " Just a pair of big primes!\n", 610 | " '''\n", 611 | " p = random_prime(bitlength)\n", 612 | " q = random_prime(bitlength)\n", 613 | " return p,q # Returns both values, as a \"tuple\"" 614 | ] 615 | }, 616 | { 617 | "cell_type": "code", 618 | "execution_count": null, 619 | "metadata": { 620 | "collapsed": false 621 | }, 622 | "outputs": [], 623 | "source": [ 624 | "type(RSA_privatekey(8)) # When a function returns multiple values, the type is \"tuple\"." 625 | ] 626 | }, 627 | { 628 | "cell_type": "code", 629 | "execution_count": null, 630 | "metadata": { 631 | "collapsed": false 632 | }, 633 | "outputs": [], 634 | "source": [ 635 | "p,q = RSA_privatekey(512) # If a function outputs two values, you can assign them to two variables.\n", 636 | "print p\n", 637 | "print q" 638 | ] 639 | }, 640 | { 641 | "cell_type": "code", 642 | "execution_count": null, 643 | "metadata": { 644 | "collapsed": true 645 | }, 646 | "outputs": [], 647 | "source": [ 648 | "def RSA_publickey(p,q, e = 65537):\n", 649 | " '''\n", 650 | " Makes the RSA public key out of \n", 651 | " two prime numbers p,q (the private key), \n", 652 | " and an auxiliary exponent e. \n", 653 | " By default, e = 65537.\n", 654 | " '''\n", 655 | " N = p*q\n", 656 | " return N,e" 657 | ] 658 | }, 659 | { 660 | "cell_type": "code", 661 | "execution_count": null, 662 | "metadata": { 663 | "collapsed": false 664 | }, 665 | "outputs": [], 666 | "source": [ 667 | "N,e = RSA_publickey(p,q) # No value of e is input, so it will default to 65537\n", 668 | "\n", 669 | "print N # A big number!\n", 670 | "print e" 671 | ] 672 | }, 673 | { 674 | "cell_type": "markdown", 675 | "metadata": {}, 676 | "source": [ 677 | "### Encryption and decryption\n", 678 | "\n", 679 | "Now we explain how the public key $(N,e)$ and the private key $(p,q)$ are used to encrypt and decrypt a (numerical) message $m$. If you wish to encrypt/decrypt a text message, one case use a numerical scheme like ASCII, of course. The message should be significantly shorter than the modulus, $m < N$ (ideally, shorter than the private key primes), but big enough so that $m^e$ is much bigger than $N$ (not usually a problem if $e = 65537$). \n", 680 | "\n", 681 | "The encryption procedure is simple -- it requires just one line of Python code, using the message and public key. The ciphertext $c$ is given by the formula\n", 682 | "$$c = m^e \\text{ mod } N,$$\n", 683 | "where here we mean the \"natural representative\" of $m^e$ modulo $N$. " 684 | ] 685 | }, 686 | { 687 | "cell_type": "code", 688 | "execution_count": null, 689 | "metadata": { 690 | "collapsed": true 691 | }, 692 | "outputs": [], 693 | "source": [ 694 | "def RSA_encrypt(message, N, e):\n", 695 | " '''\n", 696 | " Encrypts message, using the public keys N,e.\n", 697 | " '''\n", 698 | " return pow(message, e, N)" 699 | ] 700 | }, 701 | { 702 | "cell_type": "code", 703 | "execution_count": null, 704 | "metadata": { 705 | "collapsed": false 706 | }, 707 | "outputs": [], 708 | "source": [ 709 | "c = RSA_encrypt(17,N,e) # c is the ciphertext.\n", 710 | "print c # A very long number!" 711 | ] 712 | }, 713 | { 714 | "cell_type": "markdown", 715 | "metadata": {}, 716 | "source": [ 717 | "To decrypt the ciphertext, we need to \"undo\" the operation of raising to the $e$-th power modulo $N$. We must, effectively, take the $e$-th root of the ciphertext, modulo $N$. This is what we studied earlier in this notebook. Namely, if $c \\equiv m^e \\text{ mod } N$ is the ciphertext, and $ef \\equiv 1$ modulo $\\phi(N)$, then\n", 718 | "$$c^f \\equiv m^{ef} \\equiv m \\text{ mod } N.$$\n", 719 | "\n", 720 | "So we must raise the ciphertext to the $f$ power, where $f$ is the multiplicative inverse of $e$ modulo $\\phi(N)$. Given a giant number $N$, it is difficult to compute the totient $\\phi(N)$. But, with the **private key** $p$ and $q$ (primes), the fact that $N = pq$ implies\n", 721 | "$$\\phi(N) = (p-1) \\cdot (q-1) = pq - p - q + 1 = N - p - q + 1.$$\n", 722 | "\n", 723 | "Armed with the private key (and the public key, which everyone has), we can decrypt a message in just a few lines of Python code." 724 | ] 725 | }, 726 | { 727 | "cell_type": "code", 728 | "execution_count": null, 729 | "metadata": { 730 | "collapsed": false 731 | }, 732 | "outputs": [], 733 | "source": [ 734 | "def RSA_decrypt(ciphertext, p,q,N,e):\n", 735 | " '''\n", 736 | " Decrypts message, using the private key (p,q) \n", 737 | " and the public key (N,e). We allow the public key N as\n", 738 | " an input parameter, to avoid recomputing it.\n", 739 | " '''\n", 740 | " tot = N - (p+q) + 1\n", 741 | " f = mult_inverse(e,tot) # This uses the Euclidean algorithm... very quick!\n", 742 | " return pow(ciphertext,f,N)" 743 | ] 744 | }, 745 | { 746 | "cell_type": "code", 747 | "execution_count": null, 748 | "metadata": { 749 | "collapsed": false 750 | }, 751 | "outputs": [], 752 | "source": [ 753 | "RSA_decrypt(c, p,q,N,e) # We decrypt the ciphertext... what is the result?" 754 | ] 755 | }, 756 | { 757 | "cell_type": "markdown", 758 | "metadata": {}, 759 | "source": [ 760 | "That's the entire process of encryption and decryption. Encryption requires just the public key $(N,e)$ and decryption requires the private key $(p,q)$ too. Everything else is modular arithmetic, using Euler's theorem and the Euclidean algorithm to find modular multiplicative inverses.\n", 761 | "\n", 762 | "From a practical standpoint, there are many challenges, and we just mention a few here.\n", 763 | "\n", 764 | "**Key generation:** The person who constructs the private key $(p,q)$ needs to be careful. The primes $p$ and $q$ need to be pretty large (512 bits, or 1024 bits perhaps), which is not so difficult. They also need to be constructed **randomly**. For imagine that Alice comes up with her private key $(p,q)$ and Anne comes up with her private key $(q,r)$, with the same prime $q$ in common. Their public keys will include the numbers $N = pq$ and $M = qr$. If someone like Arjen comes along and starts taking GCDs of all the public keys in a database, that person will stumble upon the fact that $GCD(N,M) = q$, from which the private keys $(p,q)$ and $(q,r)$ can be derived. And this sort of disaster has happened! Poorly generated keys were stored in a database, and [discovered by Arjen Lenstra et al.](https://eprint.iacr.org/2012/064.pdf).\n", 765 | "\n", 766 | "**Security by difficulty of factoring:** The security of RSA is based on the difficulty of obtaining the private key $(p,q)$ from the public key $(N,e)$. Since $N = pq$, this is precisely the difficulty of factoring a large number $N$ into two primes (given the knowledge that it is the product of two primes). Currently it seems very difficult to factor large numbers. The RSA factoring challenges give monetary rewards for factoring such large $N$. The record (2017) is factoring a [768-bit (232 digit) number, RSA-768](https://en.wikipedia.org/wiki/RSA_numbers#RSA-768). For this reason, we may consider a 1024-bit number secure for now (i.e. $p$ and $q$ are 512-bit primes), or use a 2048-bit number if we are paranoid. If quantum computers develop sufficiently, they could make factoring large numbers easy, and RSA will have to be replaced by a quantum-secure protocol. \n", 767 | "\n", 768 | "**Web of Trust:** Trust needs to begin somewhere. Every time Alice and Bob communicate, Alice should not come up with a new private key, and give Bob the new public key. For if they are far apart, how does Bob know he's receiving Alice's public key and not talking to an eavesdropper Eve? Instead, it is better for Alice to register (in person, perhaps) her public key at some time. She can create her private key $(p,q)$ and register the resulting public key $(N,e)$ with some \"key authority\" who checks her identity at the time. The key authority then stores everyone's public keys -- effectively they say \"if you want to send a secure message to Alice, use the following public key: (..., ...)\" Then Bob can consult the key authority when he wishes to communicate securely to Alice, and this private/public key combination can be used for years.\n", 769 | "\n", 770 | "But, as one might guess, this kicks the trust question to another layer. How does Bob know he's communicating with the key authority? The key authorities need to have their own authentication mechanism, etc.. One way to avoid going down a rabbithole of mistrust is to *distribute* trust across a network of persons. Instead of a centralized \"key authority\", one can distribute one's public keys across an entire network of communicators (read about [openPGP](https://en.wikipedia.org/wiki/Pretty_Good_Privacy#OpenPGP)). Then Bob, if he wishes, can double-check Alice's public keys against the records of numerous members of the network -- assuming that hackers haven't gotten to all of them! \n", 771 | "\n", 772 | "In practice, some implementations of RSA use a more centralized authority and others rely on a web of trust. Cryptography requires a clever application of modular arithmetic (in Diffie-Hellman, RSA, and many other systems), but also a meticulous approach to implementation. Often the challenges of implementation introduce new problems in number theory." 773 | ] 774 | }, 775 | { 776 | "cell_type": "markdown", 777 | "metadata": {}, 778 | "source": [ 779 | "### Digital signatures\n", 780 | "\n", 781 | "A variant of RSA is used to \"digitally sign\" a document. Not worrying about keeping a message private for now, suppose that Alice wants to send Bob a message and **sign** the message in such a way that Bob can be confident it was sent by Alice. \n", 782 | "\n", 783 | "Alice can digitally sign her message by first **hashing** the message and then encrypting the hash using her **private key** (previously the *public key* was used for encryption -- this is different!). Hashing a message is an irreversible process that turns a message of possibly long length into a nonsense-message of typically fixed length, in such a way that the original message cannot be recovered from the nonsense-message. \n", 784 | "\n", 785 | "There is a science to secure hashing, which we don't touch on here. Instead, we import the `sha512` hashing function from the Python standard package `hashlib`. The input to `sha512` is a string of arbitrary length, and the output is a sequence of 512 bits. One can convert those 512 bits into 64 bytes (512/8 = 64) which can be viewed as a 64-character string via ASCII. This 64-byte string is called the *digest* of the hash. Note that many of the characters won't display very nicely, since they are out of the code range 32-126!" 786 | ] 787 | }, 788 | { 789 | "cell_type": "code", 790 | "execution_count": null, 791 | "metadata": { 792 | "collapsed": false 793 | }, 794 | "outputs": [], 795 | "source": [ 796 | "from hashlib import sha512\n", 797 | "\n", 798 | "print sha512(\"I like sweet potato hash.\").digest() # A 64-character string of hash." 799 | ] 800 | }, 801 | { 802 | "cell_type": "markdown", 803 | "metadata": {}, 804 | "source": [ 805 | "Hashes are designed to be irreversible. Nobody should be able to reverse the hashing process and recover the original string ('I like sweet potato hash') from the output of sha512. Moreover, hashes should avoid collisions -- although different input strings *can* yield the same hashed result, such \"collisions\" should be exceedingly rare in practice. You can read more about [SHA-512 and others at Wikipedia](https://en.wikipedia.org/wiki/SHA-2).\n", 806 | "\n", 807 | "Now, if Alice wishes to sign a message `m`, and send it to Bob, she goes through the following steps (in the RSA signature protocol).\n", 808 | "\n", 809 | "1. Alice hashes her message using a method such as SHA-512. Let `h` be the resulting hash.\n", 810 | "\n", 811 | "2. Alice **encrypts** the hash by computing $s = h^f$ modulo $N$. Here $f$ is the multiplicative inverse of $e$ modulo $\\phi(N)$, just as it was in RSA encryption. Note that this step requires knowledge of the private key $(p,q)$ to compute $\\phi(N)$ to compute $f$. Hence only Alice can encrypt the has in this way.\n", 812 | "\n", 813 | "3. Alice sends this encrypted hash along with her message to Bob, along with a note that she signed it using SHA-512 and her RSA key (without revealing her private keys, of course!).\n", 814 | "\n", 815 | "When Bob receives the (plaintext) message $m$ and signature $s$, he carries out the following authentication process.\n", 816 | "\n", 817 | "1. Bob computes $s^e$ modulo $N$. Since $s^e = h^{fe} = h$ modulo $N$, Bob now has the hash of the message $h$. \n", 818 | "\n", 819 | "2. Bob also computes the SHA-512 hash of the received message $m$, and compares it to the has he computed in step 1. If they match, then Alice indeed signed the message he received.\n", 820 | "\n", 821 | "We leave implementation of this process to the exercises." 822 | ] 823 | }, 824 | { 825 | "cell_type": "markdown", 826 | "metadata": {}, 827 | "source": [ 828 | "### Exercises\n", 829 | "\n", 830 | "1. Why might the exponent $e = 65537$ be a computationally convenient choice? Consider Pingala's algorithm.\n", 831 | "\n", 832 | "2. What would happen if the message $m$ encrypted by RSA were *equal* to one of these primes of the private key? How might such an occurrence be avoided, and is this something to be concerned about in practice?\n", 833 | "\n", 834 | "3. Look at the technical document [on OpenPGP](https://tools.ietf.org/html/rfc4880), and try to figure out how RSA and/or other cryptosystems are being used and implemented in practice. Write a 1-2 paragraph nontechnical summary of your findings.\n", 835 | "\n", 836 | "4. Suppose that you choose $M$ prime numbers at random between $2^{b-1}$ and $2^{b}$. Assuming that prime numbers near $x$ have a density $1 / \\log(x)$, estimate the probability that there is a \"collision\" -- that at least two of the $M$ prime numbers are the same. What is this probability when $b = 512$ and $M$ is two billion? (E.g., if a billion people use a pair of 512-bit private keys). Look up the \"Birthday Problem\" for some hints if you haven't seen this before.\n", 837 | "\n", 838 | "5. Create a function `sign(message, p,q,N,e)` to carry out the RSA signature protocol described above, based on a private key $(p,q)$ with public key $(N,e)$. Create a function `verify(message, signature, N, e)` to verify a signed message. Use the SHA-512 algorithm throughout, and check that your functions work.\n", 839 | "\n" 840 | ] 841 | }, 842 | { 843 | "cell_type": "code", 844 | "execution_count": null, 845 | "metadata": { 846 | "collapsed": true 847 | }, 848 | "outputs": [], 849 | "source": [] 850 | } 851 | ], 852 | "metadata": { 853 | "kernelspec": { 854 | "display_name": "Python 2", 855 | "language": "python", 856 | "name": "python2" 857 | }, 858 | "language_info": { 859 | "codemirror_mode": { 860 | "name": "ipython", 861 | "version": 2 862 | }, 863 | "file_extension": ".py", 864 | "mimetype": "text/x-python", 865 | "name": "python", 866 | "nbconvert_exporter": "python", 867 | "pygments_lexer": "ipython2", 868 | "version": "2.7.13" 869 | } 870 | }, 871 | "nbformat": 4, 872 | "nbformat_minor": 0 873 | } 874 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python-for-number-theory 2 | 3 | This repository contains a series of introductory instructional python notebooks, for computational number theory. It is designed to introduce the Python programming languages to students who have (1) never programmed before and (2) are studying number theory. It accompanies the book [An Illustrated Theory of Numbers](http://bookstore.ams.org/mbk-105), by [Martin H. Weissman](http://martyweissman.com). See [The book homepage](http://illustratedtheoryofnumbers.com/) for more details about the book, and [The programming tutorial](http://illustratedtheoryofnumbers.com/prog.html) for more about these notebooks and learning Python. 4 | 5 | Those who are teaching elementary number theory, with or without the book, may be interested in using the notebooks with students. They proceed through standard programming concepts: variables, types, simple data structures, loops, control statements, functions. At the same time they implement important number theoretic algorithms such as the Euclidean algorithm, prime factorization and primality testing, various algorithms in modular arithmetic, etc. 6 | 7 | All notebooks are free to download and edit under a GPLv3. Please read the [LICENSE](https://github.com/MartyWeissman/Python-for-number-theory/blob/master/LICENSE) for more information. 8 | --------------------------------------------------------------------------------