Hashids is a small open-source library that generates short, unique, non-sequential ids from numbers.
It converts numbers like 347 into strings like “yr8”, or array of numbers like [27, 986] into “3kTMd”.
You can also decode those ids back. This is useful in bundling several parameters into one or simply using them as short UIDs.
hd := hashids.NewData()
hd.Salt = "this is my salt"
h := hashids.NewWithData(hd)
id, _ := h.Encode([]int{1, 2, 3})
numbers, _ := h.DecodeWithError(id)
Features
Create short unique ids from numbers (positive numbers & zero).
Allow custom alphabet as well as salt — so ids are unique only to you.
Incremental input is mangled to stay unguessable.
Code is tiny (~350 lines), fast and does not depend on external libraries.
How does it work?
Hashids works similarly to the way integers are converted to hex, but with a few exceptions:
The alphabet is not base16, but base base62 by default.
The alphabet is also shuffled based on salt.
This JavaScript function shows regular conversion of integers to hex. It's part of Hashids (although this is a modified example):
JavaScriptfunction toHex(input) {
var hash = "",
alphabet = "0123456789abcdef",
alphabetLength = alphabet.length;
do {
hash = alphabet[input % alphabetLength] + hash;
input = parseInt(input / alphabetLength, 10);
} while (input);
return hash;
}
What not to do
Do not try to encode negative numbers. It won't work. The library currently supports only positive numbers and zero. If you're trying to use numbers as flags for something, simply designate the first N number of digits as internal flags.
Do not encode strings. We've had several requests to add this feature — "it seems so easy to add". We will not add this feature for security purposes, doing so encourages people to encode sensitive data, like passwords. This is the wrong tool for that.
Do not encode sensitive data. This includes sensitive integers, like numeric passwords or PIN numbers. This is not a true encryption algorithm. There are people that dedicate their lives to cryptography and there are plenty of more appropriate algorithms: bcrypt, md5, aes, sha1, blowfish. Here's a full list.
有话要说