首先你创建一个盐。
注意示例是用 PHP 编写的
// Setup a salt, this isn't "random" but it doesn't really have to be
$salt = sha1(microtime());
然后给密码加盐
// First we hash the password, then XOR it with the salt hashing the result
$hash = sha1(sha1($password) ^ $salt);
将$hash 和$salt 存储在数据库中。
当用户输入密码时,将其与哈希进行比较
if(sha1(sha1($entered_password) ^ $salt) == $hash)
// Correct password
切勿以可逆格式存储密码。另外我建议不要使用 MD5 作为哈希。
编辑:除了密码,在用户中
系统,还有什么要加密的
作为一个好习惯?他们是否加密
用户名还是其他?
密码没有加密,它们是经过哈希处理的。将散列(非常简单化)想象为接受一个数字并将其乘以 10 的东西。假设我想对数字30 进行哈希处理。我会说30*10 并得到300 作为30 的“哈希”。请注意,在不知道哈希函数如何工作的情况下,您无法从 300 派生 30。
这是一个非常简单的“哈希”,如果您知道它总是乘以 1,那么您可以轻松地将其反转。 Now take a look at the SHA1 hash function。它要复杂得多。不能简单地逆转。
你会发现除了密码散列之外很少有任何东西,并且没有任何东西是加密的。加密数据库的开销将是巨大的。
我假设您可以将类似的盐/哈希模式应用于用户名,但是您会遇到陷阱。如果您想在代码中的某处使用该用户名怎么办?如果您想检查以确保它对表是唯一的怎么办?
第二次编辑:什么是单向哈希?一世
意思是,从技术上讲,我不能逆转
设计我的源代码?也许这是
一个不好的问题,因为我不知道
很多关于单向哈希的内容。
见上文 (or click here)。单向哈希就是这样。一种方式映射。 A => B 仅此而已。 B !=> A 和 A 不能是 B 之外的任何内容。
有人提到了XOR 操作的性能。虽然我觉得性能在很大程度上可以忽略不计,但我进行了快速测试。
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
现在运行
$start_time = $this->microtime_float();
for($i = 0; $i < 100000; $i++)
{
$sha = sha1(sha1(microtime()) . sha1(microtime()));
}
$end_time = $this->microtime_float();
echo "1000 in " . ($end_time-$start_time) . " for CAT\n";
$start_time = $this->microtime_float();
for($i = 0; $i < 100000; $i++)
{
$sha = sha1(sha1(microtime()) ^ sha1(microtime()));
}
$end_time = $this->microtime_float();
echo "1000 in " . ($end_time-$start_time) . " for XOR\n";
尽可能多地重复。 initial writeup 使用错误日志,我得到以下结果:
1000 in 0.468002796173 XOR
1000 in 0.465842008591 XOR
1000 in 0.466115951538 XOR
1000 in 0.498080968857 CAT
1000 in 0.506876945496 CAT
1000 in 0.500174045563 CAT