在軟件開發中 id 通常爲 int 或者 long 類型,有時會有混淆 id 的需求,比如反爬蟲。Hashids 是一個小型的開源庫,可以將數字或者十六進制字符串轉換成唯一的、非順序的 id。
使用
添加依賴
<dependency>
<groupId>org.hashids</groupId>
<artifactId>hashids</artifactId>
<version>1.0.3</version>
</dependency>
編碼一個數字
Hashids hashids = new Hashids("this is my salt");
String hash = hashids.encode(12345L);
// 結果:NkK9
解碼一個數字
Hashids hashids = new Hashids("this is my salt");
long[] numbers = hashids.decode("NkK9");
編碼幾個數字
Hashids hashids = new Hashids("this is my salt");
String hash = hashids.encode(683L, 94108L, 123L, 5L);
// 結果:aBMswoO2UB3Sj
指定編碼結果的最小長度
Hashids hashids = new Hashids("this is my salt", 8);
String hash = hashids.encode(1L);
// 結果:gB0NV05e
指定編碼結果使用的字母表
Hashids hashids = new Hashids("this is my salt", 0, "0123456789abcdef");
String hash = hashids.encode(1234567L);
// 結果:b332db5
編碼十六進制字符串
Hashids hashids = new Hashids("This is my salt");
String hash = hashids.encodeHex("507f1f77bcf86cd799439011");
// 結果:goMYDnAezwurPKWKKxL2
解碼十六進制字符串
Hashids hashids = new Hashids("This is my salt");
String objectId = hashids.decodeHex(hash);
注意事項
Java 版本是基於 JS 版本實現,因爲 JS 對數字的範圍限制是 2^53 - 1 (9007199254740991),爲了保持兼容,Java 版本也保留了此限制,如果大於此數字將拋出 IllegalArgumentException 異常。
如果想要編碼大於 9007199254740991 的數字可以使用編碼十六進制字符串的方法。