已经在PHP中使用crypt创建了一个哈希密码,并希望在Python中使用crypt模块进行哈希处理。我怎么能做到呢?在
这是我的PHP代码:function generateSalt($cost = 10) {
if (!is_numeric($cost) || $cost < 4 || $cost > 31) {
throw new CException(Yii::t('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;
}
function _hashPassword($password, $salt) {
return crypt($password, $salt);
}
$salt = generateSalt();
$pass = _hashPassword('password', $salt);
echo $salt . '
'.PHP_EOL;
echo $pass . '
'.PHP_EOL;
输出:
^{pr2}$
并在Python中试用:import crypt
def generate_password_salt(cost=10):
if not isinstance(cost, int) or cost < 4 or cost > 31:
raise ValueError('Cost parameter must be between 4 and 31.')
import random, time, hashlib, base64
rand = ''
for _ in range(12):
rand += str(random.choice('ABCDE0123456789'))
rand += str(time.time())
sha1 = hashlib.sha1()
sha1.update(rand)
rand = sha1.digest()
return base64.b64encode(rand)[:22].replace('+', '.')
salt = generate_password_salt()
print(salt)
crpt = crypt.crypt('password', '$2$a10$%s$' % salt)
print(crpt)
获得与PHP不同的输出:UD8M0q9ufdsr/yqPvgUM2m
None
现在,我希望在Python中得到与上面的PHP相同的输出结果