在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 . '<br>'.PHP_EOL;
echo $pass . '<br>'.PHP_EOL;
输出:
$2a$10$Vz1UEa7iImWZ8WN1GVkPtH
$2a$10$Vz1UEa7iImWZ8WN1GVkPt.ZmpAHNOgoR6Xt68WAvT.1TkqaLgeFVu
在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相同