Skip to content

Commit be9e6e1

Browse files
committed
finished 0021
1 parent 7b17368 commit be9e6e1

File tree

1 file changed

+53
-4
lines changed

1 file changed

+53
-4
lines changed

jiangqideng/python练习题(答案).ipynb

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2305,13 +2305,62 @@
23052305
]
23062306
},
23072307
{
2308-
"cell_type": "code",
2309-
"execution_count": null,
2308+
"cell_type": "markdown",
23102309
"metadata": {
23112310
"collapsed": true
23122311
},
2313-
"outputs": [],
2314-
"source": []
2312+
"source": [
2313+
"### 第0021题\n",
2314+
"\n",
2315+
"通常,登陆某个网站或者 APP,需要使用用户名和密码。密码是如何加密后存储起来的呢?请使用 Python 对密码加密。\n",
2316+
"\n",
2317+
"+ 阅读资料 [用户密码的存储与 Python 示例](http://zhuoqiang.me/password-storage-and-python-example.html)\n",
2318+
"\n",
2319+
"+ 阅读资料 [Hashing Strings with Python](http://pythoncentral.io/hashing-strings-with-python/)\n",
2320+
"\n",
2321+
"+ 阅读资料 [Python's safest method to store and retrieve passwords from a database](http://stackoverflow.com/questions/2572099/pythons-safest-method-to-store-and-retrieve-passwords-from-a-database)"
2322+
]
2323+
},
2324+
{
2325+
"cell_type": "code",
2326+
"execution_count": 33,
2327+
"metadata": {
2328+
"collapsed": false
2329+
},
2330+
"outputs": [
2331+
{
2332+
"name": "stdout",
2333+
"output_type": "stream",
2334+
"text": [
2335+
"my_password: 12345678\n",
2336+
"hashed: �m���byjJ�\u0018��=5��S��I�>��o�P}iFAZ!��h�^\n",
2337+
"True\n",
2338+
"False\n"
2339+
]
2340+
}
2341+
],
2342+
"source": [
2343+
"import os\n",
2344+
"from hashlib import sha256\n",
2345+
"from hmac import HMAC\n",
2346+
"\n",
2347+
"def encrypt_password(password, salt=None):\n",
2348+
" if salt is None:\n",
2349+
" salt = os.urandom(8)\n",
2350+
" for i in xrange(10):\n",
2351+
" result = HMAC(password, salt, sha256).digest()\n",
2352+
" return salt + result\n",
2353+
"\n",
2354+
"def validate_password(hashed, input_password):\n",
2355+
" return hashed == encrypt_password(input_password, salt=hashed[:8])\n",
2356+
"\n",
2357+
"my_password = '12345678'\n",
2358+
"hashed = encrypt_password(my_password)\n",
2359+
"print 'my_password:', my_password\n",
2360+
"print 'hashed: ', hashed\n",
2361+
"print validate_password(hashed, my_password)\n",
2362+
"print validate_password(hashed, '1234567')"
2363+
]
23152364
}
23162365
],
23172366
"metadata": {

0 commit comments

Comments
 (0)