2015-11-25 22 views
5

Sto cercando di utilizzare Bcrypt per crittografare le password fornite dagli utenti al momento della registrazione e quindi utilizzare Bcrypt per convalidare una password che un utente fornisce al momento dell'accesso alla versione con hash memorizzata nel database.Come utilizzare Bcrypt per crittografare le password in Django

C'è una buona documentazione su come installare Bcrypt tramite il Django docs, ma in realtà non mostrano come usare Bcrypt in hash password o usare altri comandi.

Hai bisogno di importare Brcrypt da qualche parte? In tal caso, qual è la sintassi corretta per questo? Qual è la sintassi per le password di hashing e il confronto delle password hash con le password non hash?

Ho installato la libreria Bcrypted nel file settings.py e installato anche Bcrypt tramite pip. Cos'altro devo fare per usare Bcrypt?

risposta

8

Al vostro link:

L'attributo la password di un oggetto utente è una stringa in questo formato:

<algorithm>$<iterations>$<salt>$<hash>Questi sono i componenti utilizzati per memorizzare la password di un utente , separato dal carattere del simbolo del dollaro e composto da: l'algoritmo di hashing, il numero di algoritmi iterazioni (fattore lavoro), t ha salt saltato, e l'hash della password risultante . L'algoritmo è uno di un numero di hashing a una via o password algoritmi di archiviazione che Django può usare; vedi sotto. Le iterazioni descrivono il numero di volte che l'algoritmo viene eseguito tramite l'hash. Salt è il seme casuale utilizzato e l'hash è il risultato della funzione unidirezionale.


ho installato la libreria Bcrypted nel file settings.py ... Che altro devo fare per utilizzare Bcrypt?

Non sono sicuro di cosa significhi quella prima frase. Hai bisogno di mettere quanto segue in settings.py:

PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 
    'django.contrib.auth.hashers.BCryptPasswordHasher', 
    'django.contrib.auth.hashers.PBKDF2PasswordHasher', 
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 
    'django.contrib.auth.hashers.SHA1PasswordHasher', 
    'django.contrib.auth.hashers.MD5PasswordHasher', 
    'django.contrib.auth.hashers.CryptPasswordHasher', 
) 

uso Bcrypt per convalidare una password di un utente fornisce al login contro la versione hash memorizzato nel database.

È possibile farlo manualmente:

Il modulo django.contrib.auth.hashers fornisce una serie di funzioni per creare e convalidare la password hash. È possibile utilizzarli indipendentemente dal modello Utente.

check_password (password, codificata)
Se vuoi per autenticare manualmente un utente confrontando una password di testo normale alla hash password nel database, utilizzare la funzione di convenienza check_password().Sono necessari due argomenti: la password in chiaro al controllo e il valore completo del campo della password di un utente nel database da verificare e restituisce True se corrispondono, False altrimenti.

https://docs.djangoproject.com/en/1.9/topics/auth/passwords/#module-django.contrib.auth.hashers

In alternativa, è possibile utilizzare authenticate():

autenticazione (**) le credenziali
per autenticare il nome utente e la password, l'uso authenticate(). Accetta credenziali sotto forma di argomenti di parole chiave , per la configurazione di default è il nome utente e la password e restituisce un oggetto Utente se la password è valida per il nome utente specificato. Se la password non è valida, authenticate() restituisce Nessuno. Esempio:

from django.contrib.auth import authenticate 

user = authenticate(username='john', password='password to check') 

if user is not None: 
    # the password verified for the user 
    if user.is_active: 
     print("User is valid, active and authenticated") 
    else: 
     print("The password is valid, but the account has been disabled!") 
else: 
    # the authentication system was unable to verify the username and password 
    print("The username and password were incorrect.") 

https://docs.djangoproject.com/en/1.9/topics/auth/default/#authenticating-users

Ecco alcuni esempi:

(django186p34)~/django_projects/dj1$ python manage.py shell 

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
(InteractiveConsole) 

>>> from django.conf import settings 
>>> print(settings.PASSWORD_HASHERS) 

('django.contrib.auth.hashers.PBKDF2PasswordHasher', 
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 
'django.contrib.auth.hashers.BCryptPasswordHasher', 
'django.contrib.auth.hashers.SHA1PasswordHasher', 
'django.contrib.auth.hashers.MD5PasswordHasher', 
'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher', 
'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher', 
'django.contrib.auth.hashers.CryptPasswordHasher') 

Queste sono le impostazioni di default: non v'è alcuna voce nella mia settings.py per PASSWORD_HASHERS.

>>> from django.contrib.auth.models import User 

>>> my_user = User.objects.create_user('ea87', '[email protected]', '666monkeysAndDogs777') 

>>> my_user.save() 
>>> my_user.password 
'pbkdf2_sha256$20000$L7uq6goI1HIl$RYqywMgPywhhku/YqIxWKbpxODBeczfLm5zthHjNSSk=' 
>>> my_user.username 
'ea87' 

>>> from django.contrib.auth import authenticate 

>>> authenticate(username='ea87', password='666monkeysAndDogs777') 
<User: ea87> 

>>> print(authenticate(username='ea87', password='wrong password')) 
None 

>>> from django.contrib.auth.hashers import check_password 

>>> check_password('666monkeysAndDogs777', my_user.password) 
True 

>>> exit() 

Successivamente, ho aggiunto il seguente al settings.py:

PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 
    'django.contrib.auth.hashers.BCryptPasswordHasher', 
    'django.contrib.auth.hashers.PBKDF2PasswordHasher', 
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 
    'django.contrib.auth.hashers.SHA1PasswordHasher', 
    'django.contrib.auth.hashers.MD5PasswordHasher', 
    'django.contrib.auth.hashers.CryptPasswordHasher', 
) 

(django186p34)~/django_projects/dj1$ python manage.py shell 

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
(InteractiveConsole) 

>>> from django.conf import settings 
>>> print(settings.PASSWORD_HASHERS) 
('django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 
'django.contrib.auth.hashers.BCryptPasswordHasher', 
'django.contrib.auth.hashers.PBKDF2PasswordHasher', 
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 
'django.contrib.auth.hashers.SHA1PasswordHasher', 
'django.contrib.auth.hashers.MD5PasswordHasher', 
'django.contrib.auth.hashers.CryptPasswordHasher') 

Nota le hashers bcrypt nella parte anteriore della tupla.

>>> from django.contrib.auth.models import User 

>>> user = User.objects.get(username='ea87') 
>>> user 
<User: ea87> 

>>> user.password 
'pbkdf2_sha256$20000$DS20ZOCWTBFN$AFfzg3iC24Pkj5UtEu3O+J8KOVBQvaLVx43D0Wsr4PY=' 

>>> user.set_password('666monkeysAndDogs777') 
>>> user.password 
'bcrypt_sha256$$2b$12$QeWvpi7hQ8cPQBF0LzD4C.89R81AV4PxK0kjVXG73fkLoQxYBundW' 

Si può vedere che la password è stata modificata in una versione di bcrypt.

+0

I upvoted, perché un sacco di idee mi ha aiutato a scoprire che cosa mi ha confuso; mettere in corto per quelli confusi in futuro: gli hash prodotti da BCrypt (che è ciò che php attualmente utilizza) non sono affatto nella forma ' $ $ $ ' come indicato nella documentazione, ma come potete vedere a la fine della risposta (solo con "_sha256", almeno questo è il modo in cui i miei hash php sono stati crittografati -> importati in django! :)) – Ilja

0

Versione corta della risposta di 7stud

Sulla Django 1.9 di default l'uso progetto modello create_user:

User.objects.create_user(username='uname', password='mypass') 

invece di create, che non hash della password.

Un'altra opzione è quella di impostare la password con:

user = User(username='uname') 
user.set_password('mypass') 
user.save() 

Infine si potrebbe anche operare su stringhe come accennato: How to quickly encrypt a password string in Django without an User Model?

Problemi correlati