LoginSignup
2
2

More than 5 years have passed since last update.

Djangoのcontrib/auth/utils.py

Last updated at Posted at 2012-12-26

( https://github.com/django/django/blob/master/django/contrib/auth/utils.py )
っぽい何かをNode.js向けに書いてみました。

var crypto = require('crypto');


exports.getSalt = function (n) {
  var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#%^&*()_+'
    , salt = '';
  for (var i = 0; i < n; i++) {
    salt = salt + chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return salt;
};

exports.getHexdigest = function (algorithm, salt, rawPassword) {
  var hash = (salt || '') + (rawPassword || '');
  for (var i = 0; i < 100; i++) {
    hash = crypto.createHmac(algorithm, hash).digest('hex');
  }
  return hash;
};

exports.getPassword = function (algorithm, rawPassword) {
  var salt = exports.getSalt(10)
    , hexdigest = exports.getHexdigest(algorithm, salt, rawPassword);
  return algorithm + '$' + salt + '$' + hexdigest;
};

exports.checkPassword = function (rawPassword, password) {
  var ary = password.split('$');
  return ary[2] === exports.getHexdigest(ary[0], ary[1], rawPassword);
};
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2