Asara
Asara

Reputation: 3374

Create a django password in a simple python script

I need to generate an encrypted password that can be used within Django in a simple python script. What package/module would I need to import to achieve that? I am looking for something like:

from django.auth import create_password_from_string

django_password = create_password_from_string('coolpassword')

The background is, that I have a PHP application on server1 which should share the accounts with a Django application on server2. When an account is created in the PHP application, I want to fire up a python script that generates the encrypted password for the django application and transfers it to server2.

Of course, creating the encrypted string by PHP would be much better for this usecase, but I bet its even harder to achieve.

Upvotes: 3

Views: 2857

Answers (2)

Alberto de Prezzo
Alberto de Prezzo

Reputation: 96

What you're looking for is make_password.

Basic usage:

Simply pass your plain-text password, it returns the hash you need.

Furthermore, according to the project reqs and specs, you can set the algorithm on the server2 app: just pass also the hasher parameter (note: in Django, the default is PBKDF2).

Environment requisites:

First of all, if you're new to Python my advice is to take a look to the PYTHONPATH env var, used to "tell" to the interpreter where he has to search. Then, using Django, if you want you can define which settings file the running instance has to point to. This is accomplished with another env var, the DJANGO_SETTINGS_MODULE, and for django-admin it can be set also inline:

django-admin runserver --settings=server2.settings

make_password example:

Assuming that your Python/Django env/path variables are properly configured, you have:

$ python manage.py shell
>>> from django.contrib.auth.hashers import make_password
>>> make_password('password', 'generate something random', 'pbkdf2_sha256')

Result:

'pbkdf2_sha256$36000$generate something random$0F6M8tj8Y65YXuUgfRkDAwYqrky6Ob5JN+HLPO+6Ayg='

Upvotes: 2

Asara
Asara

Reputation: 3374

I actually found an easy approach for PHP, which suits better for my usecase:

$password = 'password'
$salt = 'generate something random'
$iterations = 120000
$hash = base64_encode(hash_pbkdf2 ( 'sha256' , $password , $salt , $iterations, 32, true));

$django_password = 'pbkdf2_256'. '$' . $iterations . '$' . $hash;

Upvotes: 1

Related Questions