0

Generate passwords in PHP using crypt(). An example output is:

$2a$10$F47zZrxfkRN4M4djSBPKXeS5QFdOwSrHn03m40WR1rI8g1cBGHgMO

Now, I've requirement to generate passwords using PassLib in Python, that should be validated in PHP.

PHP Code:

function generateSalt($cost = 10) {
    if (!is_numeric($cost) || $cost < 4 || $cost > 31) {
        die('Cost parameter must be between 4 and 31.');
    }
    // Get some pseudo-random data from mt_rand().
    $rand = '';
    for ($i = 0; $i < 8; ++$i) {
        $rand.=pack('S', mt_rand(0, 0xffff));
    }
    // Add the microtime for a little more entropy.
    $rand .= microtime();
    // Mix the bits cryptographically.
    $rand = sha1($rand, true);
    // Form the prefix that specifies hash algorithm type and cost parameter.
    $salt = '$2a$' . str_pad((int) $cost, 2, '0', STR_PAD_RIGHT) . '$';
    // Append the random salt string in the required base64 format.
    $salt .= strtr(substr(base64_encode($rand), 0, 22), array('+' => '.'));
    return $salt;
}

crypt('apasswd', generateSalt());
// Output: $2a$10$F47zZrxfkRN4M4djSBPKXeS5QFdOwSrHn03m40WR1rI8g1cBGHgMO

I want to be able to generate the same hash with python. How can I do that ?

Vin.AI
  • 2,369
  • 2
  • 19
  • 40
  • @Marc, There is no error. Wanting same password mechanism to generate in Python too. So, I can validate users in Python application. – Vin.AI Aug 07 '14 at 09:04
  • Sorry, stackoverflow is, like the name provides, a platform to support on errors - not for free coding. The crypt/hashlib library of python is well documented. If you have any python code, I'd like to help – mrcrgl Aug 07 '14 at 14:00
  • BTW: http://stackoverflow.com/questions/8303377/porting-hashs-from-phps-crypt-to-python?rq=1 – mrcrgl Aug 07 '14 at 14:01

1 Answers1

0

You cannot do that because you are generating a hash with a random generated salt. So your final hash will be always different

Freelancer
  • 4,459
  • 2
  • 22
  • 28
  • I don't think so. Because at validation time we don't pass salt, however `crypt()` validates. e.g: `crypt('apasswd', '$2a$10$F47zZrxfkRN4M4djSBPKXeS5QFdOwSrHn03m40WR1rI8g1cBGHgMO') === '$2a$10$F47zZrxfkRN4M4djSBPKXeS5QFdOwSrHn03m40WR1rI8g1cBGHgMO'`. So, salt could be anything! – Vin.AI Aug 07 '14 at 10:47
  • So your question is wrong you don't want to generate a hash the same way you did in php. You just want to generate password without generating the salt because the salt is already generated by php – Freelancer Aug 07 '14 at 11:49