{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Introduction\n",
"\n",
"If you want to communicate safely with a website, you are probably using the RSA protocol. In this Notebook, we will implement this algorithm and try it on a simple example. \n",
"\n",
"# Principle\n",
"\n",
"Let's assume you are Amazon. You have several customer and you need to ask them secrets informations that only you should be able to decrypt. To do so, the RSA works with 2 keys :\n",
"- 1 Private key allowing you to decrypt the code\n",
"- 1 Public key to share will all users to encode the information\n",
"\n",
"When you ask the consumer for a sensitive information, they encrypt this information using the Public key and send this to the network. If someone else, receive it, they won't we able to decrypt it as they have only the public key. However, with your private key, you (and only you) can decrypt this information. That's why the private key must remain secret.\n",
"\n",
"If you are a hacker and you want to break the private key to decrypt the information you have stolen in the network, you will need to do a Prime Factorization which is a very complex problem. \n",
"\n",
"Let see how those keys are created"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"import random\n",
"from math import gcd\n",
"\n",
"def coprimes(number):\n",
" while True:\n",
" e = int(random.random() * (number - 2)) + 2 \n",
" if gcd(e, number) == 1: \n",
" break\n",
" return e\n",
"\n",
"def egcd(number, modulo):\n",
" if number == 0:\n",
" return modulo, 0, 1\n",
" else:\n",
" g, y, x = egcd(modulo % number, number)\n",
" return g, x - (modulo // number) * y, y\n",
"\n",
"\n",
"def modinv(number, modulo):\n",
" g, x, y = egcd(number, modulo)\n",
" if g != 1:\n",
" raise Exception('modular inverse does not exist')\n",
" else:\n",
" return x % modulo"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Algorithm\n",
"\n",
"The keys are created in 5 steps:\n",
"\n",
"## Step 1 : Find 2 primes number (p and q)\n",
"\n",
"They must be as big as possible because this is giving the safety of the algorithm (it's often a ~200 digit primes number). However, here, we will use smaller one just for the example."
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {},
"outputs": [],
"source": [
"p = 3\n",
"q = 11"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 2 : Compute 2 numbers (N and Phi(N))\n",
"\n",
"This step is quite obvious, there is only 2 formulas to remember \n",
"$$ N = p \\times q $$\n",
"$$ \\phi(N) = (p-1) \\times (q-1) $$"
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {},
"outputs": [],
"source": [
"n = p * q\n",
"phi = (p-1)*(q-1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 3 : Take a random number coprime (e) with $\\phi(N)$\n",
"\n",
"At this step we need to find randomly a number being coprime with $\\phi(N)$. This means that e and $\\phi(N)$ should have only 1 a common divisor. We can use the GCD algorithm to get it"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
"outputs": [],
"source": [
"e = coprimes(phi)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 4 : Find d where $ d \\times e \\equiv 1 \\pmod{ \\phi(N) } $\n",
"\n",
"This last import number is more tricky to get. It requires the computation of the Modular multiplicative inverse which is also based on the Extended Greatest Common Divisor. I used an implementation found on the internet."
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {},
"outputs": [],
"source": [
"d = modinv(e, phi)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## (Bonus) Offset d and e\n",
"\n",
"This step is not really required but it allows to hide a bit the $ \\phi(N) $ when you use it on samll value like I'm doing now. In term of safety, I don't think it helps a lot..."
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [],
"source": [
"e += int(random.random() * n) * phi"
]
},
{
"cell_type": "code",
"execution_count": 79,
"metadata": {},
"outputs": [],
"source": [
"d += int(random.random() * n) * phi"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Return the 2 keys\n",
"\n",
"The 2 keys are now easy to create :\n",
" \n",
" - One key is the pair (e, n)\n",
" - One key is the pair (d, n)\n",
" \n",
"You select the one you want as private but after you keep it secret. The second one can be shared to everybody. Let's now summary the example above"
]
},
{
"cell_type": "code",
"execution_count": 81,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"p: 3 , q: 11\n",
"N: 33\n",
"phi: 20\n",
"e: 173 , d: 57\n",
"57*173 % 20 = 1\n",
"public key : (57, 33)\n",
"private key : (173, 33)\n"
]
}
],
"source": [
"print(\"p: {} , q: {}\".format(p, q))\n",
"print(\"N: {}\".format(n))\n",
"print(\"phi: {}\".format(phi))\n",
"print(\"e: {} , d: {}\".format(e, d))\n",
"print(\"{}*{} % {} = {}\".format(d, e, phi, (d*e) % phi))\n",
"print(\"public key : {}\".format((d, n)))\n",
"print(\"private key : {}\".format((e, n)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Security\n",
"\n",
"Just as a background, as we know how to create the key, we can understand why it's dangerous to use small p and q. The key contains N = p * q.\n",
"If the hacker is able to find p and q from N. The hacker will have $ \\phi(N) $. With that he has e (or d based on the key creation) and $ \\phi(N) $. It's after very easy to find e (or d) and having the private key.\n",
"\n",
"Let's now have a look at how to encode / decode\n",
"\n",
"# Encoding\n",
"\n",
"This step is quite simple. The message you want to send must be converted to numbers. You can do the one you want but in this example, we will use the ascii code of every letter of the message.\n",
"\n",
"To encode the message you have to use the public key (let say the pair (d, n)). For every number (k) you have to pass it through the formula below $$ code = k^d\\mod{ n } $$\n",
"\n",
"# Decoding\n",
"\n",
"The decoding step is exactly the invert with you private key (e, n): $$ k = code^e\\mod{ n } $$\n",
"\n",
"After you can passe from ascii to letter easily.\n",
"\n",
"Let's do a real example\n",
"\n",
"##### NB : For this computation with large number, do not use the normal power function and modulo. You have to use instead the modpow algorithm. This is because a big number to a big power won't fit in memory. This algorithm is a lot faster. It's implemented by default in python build-in pow function"
]
},
{
"cell_type": "code",
"execution_count": 87,
"metadata": {},
"outputs": [],
"source": [
"def create_keys(p, q):\n",
" \n",
" def coprimes(number):\n",
" while True:\n",
" e = int(random.random() * (number - 2)) + 2 \n",
" if gcd(e, number) == 1: \n",
" break\n",
" return e\n",
"\n",
" def egcd(number, modulo):\n",
" if number == 0:\n",
" return modulo, 0, 1\n",
" else:\n",
" g, y, x = egcd(modulo % number, number)\n",
" return g, x - (modulo // number) * y, y\n",
"\n",
"\n",
" def modinv(number, modulo):\n",
" g, x, y = egcd(number, modulo)\n",
" if g != 1:\n",
" raise Exception('modular inverse does not exist')\n",
" else:\n",
" return x % modulo\n",
" \n",
" n = p * q\n",
" phi = (p-1)*(q-1)\n",
" e = coprimes(phi)\n",
" d = modinv(e, phi)\n",
" e += int(random.random() * n) * phi\n",
" d += int(random.random() * n) * phi\n",
" return (e, n), (d, n)\n",
"\n",
"def encode(word, public_key):\n",
" return [pow(ord(letter), public_key[0], public_key[1]) for letter in word]\n",
" \n",
"def decode(code, private_key):\n",
" decoded = [pow(value, private_key[0], private_key[1]) for value in code]\n",
" return \"\".join([chr(ascii) for ascii in decoded])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Creation of keys"
]
},
{
"cell_type": "code",
"execution_count": 83,
"metadata": {},
"outputs": [],
"source": [
"public_key, private_key = create_keys(7741, 7753)"
]
},
{
"cell_type": "code",
"execution_count": 84,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"public key : (2050183293675059, 60015973)\n",
"private key : (2325870019225499, 60015973)\n"
]
}
],
"source": [
"print(\"public key : {}\".format(public_key))\n",
"print(\"private key : {}\".format(private_key))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Encoding (customer side)\n",
"\n",
"By using the public key, we can encode the message"
]
},
{
"cell_type": "code",
"execution_count": 88,
"metadata": {},
"outputs": [],
"source": [
"code = encode(\"Hello World\", public_key)"
]
},
{
"cell_type": "code",
"execution_count": 90,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The code is : [5956990, 47214715, 21647324, 21647324, 43082101, 40738165, 15059835, 43082101, 54412267, 21647324, 47783031]\n"
]
}
],
"source": [
"print(\"The code is : {}\".format(code))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Decoding (your side)\n",
"\n",
"This code is sent to the network and now you have to decrypt it using your private key "
]
},
{
"cell_type": "code",
"execution_count": 92,
"metadata": {},
"outputs": [],
"source": [
"decoded = decode(code, private_key)"
]
},
{
"cell_type": "code",
"execution_count": 93,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The message is : Hello World\n"
]
}
],
"source": [
"print(\"The message is : {}\".format(decoded))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here it is, it worked ! However, keep in mind that this example uses very small primes and is highly unsecure. In addition, if the value $ p \\times q $ is smaller than the value you want to encode, you won't be able to decrypt it. Here we uses the value of every letter in ascii so there is no risk but in some cases, we could use bigger chunk (for example a phone number complete)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Going further\n",
"\n",
"As we saw it here, we can see limitation of this algorithm because everybody have the public key and only the one having the private key can decrypt your message. This means that there is no way for you (amazon) to send encoded message to the user (customer) as everybody have the public key and will be able to decrypt it. \n",
"\n",
"However, there is alternative to have a complete crypted communication in few steps:\n",
"- The customer generates also in his side a pair (public/private) key. \n",
"- With the Public key he has from you, he encode his own public key and send it to you\n",
"- With your private key, you can decyphter the public key he send you (and you keep your private key)\n",
"- When you want to contact the customer, you use his public key to crypt the message\n",
"- When you want to read the answer from the customer, you use your private key\n",
"- On the customer side, it's reversed.\n",
"\n",
"That's all. You only used a public key to send in a secure way a second pair of key for the other direction"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Conclusion\n",
"\n",
"In this Notebook, we saw how the most common algorithm is working to secure information on the internet. There is multiple other ones existing and I'll start to learn them."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": true,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": false
},
"varInspector": {
"cols": {
"lenName": 16,
"lenType": 16,
"lenVar": 40
},
"kernels_config": {
"python": {
"delete_cmd_postfix": "",
"delete_cmd_prefix": "del ",
"library": "var_list.py",
"varRefreshCmd": "print(var_dic_list())"
},
"r": {
"delete_cmd_postfix": ") ",
"delete_cmd_prefix": "rm(",
"library": "var_list.r",
"varRefreshCmd": "cat(var_dic_list()) "
}
},
"position": {
"height": "361.85px",
"left": "1976.67px",
"right": "20px",
"top": "120px",
"width": "350px"
},
"types_to_exclude": [
"module",
"function",
"builtin_function_or_method",
"instance",
"_Feature"
],
"window_display": true
}
},
"nbformat": 4,
"nbformat_minor": 2
}