【发布时间】:2016-10-09 00:49:12
【问题描述】:
我在我的Django 项目中使用Hashids(http://hashids.org/python/)。
我想创建固定长度的哈希。
但是Hashids只支持min_length:
hash_id = Hashids(
salt=os.environ.get("SALT"),
min_length=10,
)
如何设置hash_id 的固定长度(例如,10 个字符)?
【问题讨论】:
我在我的Django 项目中使用Hashids(http://hashids.org/python/)。
我想创建固定长度的哈希。
但是Hashids只支持min_length:
hash_id = Hashids(
salt=os.environ.get("SALT"),
min_length=10,
)
如何设置hash_id 的固定长度(例如,10 个字符)?
【问题讨论】:
虽然我没有使用过python版本的库,但我仍然觉得我可以回答,因为我正在维护.NET版本并且它们大多共享相同的算法。
只要从逻辑上考虑这一点,固定散列的长度(或设置最大长度)结合允许用户定义字母和盐,限制散列的可能变化,因此也限制哪些数字可以被编码。
我猜这就是为什么今天的图书馆不可能。
【讨论】:
您可以轻松设置 hashid 的 min_length,但设置 max_length 会比较棘手,因为这需要在整数通过。请避免在生产环境中这样做,因为这可能会对您的系统产生负面影响。下面的示例代码说明了如何为 PHP Laravel 设置 min_length 如果使用不同的语言请根据您使用的语言检查 hashid 实现。
namespace App\Hashing;
use Hashids\Hashids;
class Hash {
private $salt_key;
private $min_length;
private $hashid;
public function __construct(){
$this->salt_key = '5OtYLj/PtkLOpQewWdEj+jklT+oMjlJY7=';
$this->min_length = 15;
$this->hashid = new Hashids($this->salt_key, $this->min_length);
}
public function encodeId($id){
$hashed_id = $this->hashid->encode($id);
return $hashed_id;
}
public function decodeId($hashed_id){
$id = $this->hashid->decode($hashed_id);
return $id;
}
}
$hash = new Hash();
$hashed_id = $hash->encodeId(1);
echo '<pre>';
print_r($hashed_id);
echo '</pre>';
echo "<pre>";
$id = $hash->decodeId($hashed_id);
print_r($id[0]);
echo "</pre>";
【讨论】:
您可以在Hashids中设置“min_length”
例如:
hashids = Hashids(min_length=16, salt="my salt")
hashid = hashids.encode(1) # '4q2VolejRejNmGQB'
更多详情请点击here
【讨论】: