2

我在我的项目中使用Hashidshttp://hashids.org/python/) 。Django

我想创建固定长度的哈希。

Hashids仅支持min_length

hash_id = Hashids(
    salt=os.environ.get("SALT"),
    min_length=10,
)

如何设置固定长度(比如 10 个字符)hash_id

4

3 回答 3

5

While I haven't used the python version of the library, I still feel that I can answer since I'm maintaining the .NET version and they mostly share the same algoritm.

Just thinking of this logically, fixing the length of the hash (or setting a max-length) in combination with allowing the user to define alphabet and salt, limits the possible variations of the hash and therefor also limiting which numbers that can be encoded.

I am guessing that's why it isn't possible with the library today.

于 2016-10-13T06:40:58.283 回答
0

您可以轻松设置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>";
于 2019-06-06T11:06:24.280 回答
-1

您可以在 Hashids 中设置“min_length”

例如:

hashids = Hashids(min_length=16, salt="my salt")
hashid = hashids.encode(1) # '4q2VolejRejNmGQB'

更多详情请点击这里

于 2018-09-17T12:36:42.310 回答