Commit b451e946 authored by Matthias Endler's avatar Matthias Endler

Initial commit

parents
# PyGraz March 2019 Lighting Talk Secrets Module
This was a lighting talk held at the March 2019 PyGraz Meetup.
## License
<a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>.
The source of the file <words_alpha.txt> can be found [here](https://github.com/dwyl/english-words/blob/master/words_alpha.txt),
and it is licensed under the [Unlicense](https://raw.githubusercontent.com/dwyl/english-words/master/LICENSE.md).
---
Copyright &#169; 2019, Matthias Endler. All rights reserved.
\ No newline at end of file
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# The `secrets` Module\n",
"\n",
"The `secrets` module is in the Python standard library since version `3.6`. It i can be used to generate cryptographically secure randoms of various kinds."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Creating random integers"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import secrets\n",
"\n",
"# random integer 0 .. n - 1. In this example we roll a dice :-)\n",
"secrets.randbelow(6) + 1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"20638"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import secrets\n",
"\n",
"# random integer of n random bits in this example 0 to 2**15 - 1\n",
"secrets.randbits(15)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Creating random tokens"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"b'\\xa6)\\x0fm\\xd7n\\t\\x95j\\x87\\xec\\xb0\\xc3\\xa5\\xe1\\x07\\x08\\x9b\\xddF[\\x81\\x8c\\xa5\\xe8\\x9b[\\xea\\x1a_\\x16$'"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import secrets\n",
"\n",
"\n",
"secrets.token_bytes()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'vzwe-S_STi_vceubkGvEV4nh3j_LMAB8gz8pE9IZAmY'"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import secrets\n",
"\n",
"\n",
"secrets.token_urlsafe()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'0b5791ddcce6a922e1ac716c0a6adc2f0f31a642e6eef61dbf2de8d293a5e1f8'"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import secrets\n",
"\n",
"\n",
"secrets.token_hex()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A function to compare two tokens in constant time\n",
"\n",
"With `secrets.compare_digest` you can compare two tokens in constant time, to avoid timing attacks. Only the length of a secret token can be found out by the timing attack."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import secrets\n",
"\n",
"\n",
"secrets.compare_digest(b'123456789', b'123456789')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create random passwords and pins for use in FreeSWITCH\n",
"\n",
"[FreeSWITCH](https://freeswitch.org) is a scalable open source cross-platform telephony platform designed to route and interconnect popular communication protocols using audio, video, text or any other form of media."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'password': 'wpRempVLA7s4gsjY',\n",
" 'passwordHash': 'cfa669a7f948d018f7725bbde17eec31',\n",
" 'pin': '83054',\n",
" 'pinHash': '916fc81bf59369ca83f601d27c73d6b3'}"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from hashlib import md5\n",
"import secrets\n",
"import string\n",
"\n",
"\n",
"def random_password(length=None):\n",
" length = 8 if length is None else length\n",
" if length < 8:\n",
" raise ValueError('length must be at least 8')\n",
" seq = string.ascii_letters + string.digits\n",
" return ''.join([secrets.choice(seq) for _ in range(length)])\n",
"\n",
"\n",
"def random_pin(length=None):\n",
" length = 5 if length is None else length\n",
" if length < 4:\n",
" raise ValueError('length must be at least 4')\n",
" seq = string.digits\n",
" pin = ''.join([secrets.choice(seq) for _ in range(length)])\n",
" if pin[0]*length == pin:\n",
" random_pin(length)\n",
" return pin\n",
"\n",
"\n",
"def a1_hash(user_part, realm, secret):\n",
" cleartext = '{:s}:{:s}:{:s}'.format(user_part, realm, secret)\n",
" hashed = md5(cleartext.encode(encoding='utf-8'))\n",
" return hashed.hexdigest()\n",
"\n",
"\n",
"password = random_password(16)\n",
"password_hash = a1_hash('john.doe', 'example.com', password)\n",
"pin = random_pin()\n",
"pin_hash = a1_hash('john.doe', 'example.com', pin)\n",
"{\n",
" 'password': password,\n",
" 'passwordHash': password_hash,\n",
" 'pin': pin,\n",
" 'pinHash': pin_hash,\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use word list for password creation\n",
"\n",
"[word list source](https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"exclave nested searer cunza aerogel\n"
]
}
],
"source": [
"import secrets\n",
"\n",
"\n",
"with open('words_alpha.txt', 'r') as f:\n",
" words = f.readlines()\n",
" print(' '.join([secrets.choice(words).strip() for _ in range(5)]))"
]
}
],
"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.7.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
This diff is collapsed.
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment