最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Django自带加密模块的使用
时间:2014-04-03 编辑:简简单单 来源:一聚教程网
代码如下 | 复制代码 |
Manually managing a user’s password
The django.contrib.auth.hashers module provides a set of functions to create and validate hashed password. You can use them independently from the User model.
check_password(password, encoded)
If you’d like to manually authenticate a user by comparing a plain-text password to the hashed password in the database, use the convenience function check_password(). It takes two arguments: the plain-text password to check, and the full value of a user’s password field in the database to check against, and returns True if they match, False otherwise.
Changed in Django 1.6:
In Django 1.4 and 1.5, a blank string was unintentionally considered to be an unusable password, resulting in this method returningFalse for such a password.
make_password(password[, salt, hashers])
Creates a hashed password in the format used by this application. It takes one mandatory argument: the password in plain-text. Optionally, you can provide a salt and a hashing algorithm to use, if you don’t want to use the defaults (first entry of PASSWORD_HASHERS setting). Currently supported algorithms are: 'pbkdf2_sha256', 'pbkdf2_sha1', 'bcrypt_sha256'(see Using bcrypt with Django), 'bcrypt', 'sha1', 'md5', 'unsalted_md5' (only for backward compatibility) and 'crypt' if you have the crypt library installed. If the password argument is None, an unusable password is returned (a one that will be never accepted by check_password()).
|
首先,引入模块:
代码如下 | 复制代码 |
>>> from django.contrib.auth.hashers import make_password, check_password 生成密码: |
这样就可以利用django自带的模块生成一组密码了,这个函数还有一个特点在于每次生成的密码还不一样:
代码如下 | 复制代码 |
|
既然每次生成的密文都不一样,如何验证用户提交过来的明文与密文匹配呢?这就靠check_password去做了,check_password使用非常简单,只需要告诉它明文和密文它就会返回False or True验证结果
代码如下 | 复制代码 |
|
如果你不想每次都生成不同的密文,可以把make_password的第二个函数给一个固定的字符串,比如:
代码如下 | 复制代码 |
>>> make_password(text, "a", 'pbkdf2_sha256') u'pbkdf2_sha256$12000$a$5HkIPczRZGSTKUBa5uzZmRuAWdp2Qe6Oemhdasvzv4Q=' >>> make_password(text, "a", 'pbkdf2_sha256') u'pbkdf2_sha256$12000$a$5HkIPczRZGSTKUBa5uzZmRuAWdp2Qe6Oemhdasvzv4Q=' |
只要是任意字符串就可以,并且可以多个。但不能为空,如:
代码如下 | 复制代码 |
|
为空的字符串就相当于:
1
代码如下 | 复制代码 |
make_password(text, None, 'pbkdf2_sha256') |
至于make_password第三个参数是表示生成密文的一种方式,根据文档给出的大概有这几种:
代码如下 | 复制代码 |
pbkdf2_sha256 |
以上例子我使用了第一种加密方式pbkdf2_sha256,crypt和bcrypt都需要另外单独安装模块,unsalted_md5就是常见的md5加密,如果对加密哈希算法不是很了解,那么就使用django最新的哈希算法pbkdf2_sha256就好
相关文章
- word文档怎么加密 07-01
- python基于pyDes库怎么实现des加密 05-03
- word文档加密方法 04-18
- 加密CAD图纸教程 04-14
- 对称加密与非对称加密优缺点详解 03-16
- java怎么使用md5加密?java中使用MD5进行加密的方法 02-17