|
2305 | 2305 | ]
|
2306 | 2306 | },
|
2307 | 2307 | {
|
2308 |
| - "cell_type": "code", |
2309 |
| - "execution_count": null, |
| 2308 | + "cell_type": "markdown", |
2310 | 2309 | "metadata": {
|
2311 | 2310 | "collapsed": true
|
2312 | 2311 | },
|
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 | + ] |
2315 | 2364 | }
|
2316 | 2365 | ],
|
2317 | 2366 | "metadata": {
|
|
0 commit comments