寫在前面
- 之前寫網絡爬蟲程式時發現,大部分的爬取位址的參數都是有規律的數字;
- 通過這個發現,其實可以基于這個數字做加密,以此來反爬取;
- hashids有多語言的實作,這裡講的是基于python語言;
- 據了解,Youtube網站就是這麼做的。
hashids介紹
- hashids庫安裝:
pip install hashids
- 如下,Hashids類的構造參數中salt其實是設定的私鑰,通過這個私鑰,将數字轉換成一串看上去無規則的字元串,解碼後是一個元組的形式;
>>> import hashids >>> hashandle = hashids.Hashids(salt="secretkey") >>> hashandle.encode(123456) 'E57VB' >>> hashandle.decode("E57VB") (123456,)
- 另外,encode方法的傳參還可以是多個數字,同樣可以做加密和解密;
>>> hashandle.encode(12,34,56,78) 'k6u8hN3IwV' >>> hashandle.decode("k6u8hN3IwV") (12, 34, 56, 78) >>>
- 如下是hashids這個庫源碼中的構造器部分,還可以設定生成字元串的最小長度,對應的映射資料等。
class Hashids(object): """Hashes and restores values using the "hashids" algorithm.""" ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' def __init__(self, salt='', min_length=0, alphabet=ALPHABET): """ Initializes a Hashids object with salt, minimum length, and alphabet. :param salt: A string influencing the generated hash ids. :param min_length: The minimum length for generated hashes :param alphabet: The characters to use for the generated hash ids. """ self._min_length = max(int(min_length), 0) self._salt = salt
小結
維基百科提到一個理想的hash算法需要滿足下面3個特性
- 正向計算hash很容易
- 反向破解hash極其困難
- hash值碰撞機率極小
hashids庫實作了第一點和第三點,第二點取決于私鑰的擷取難易;
相對于md5的不可逆加密,hashids庫實作的是加解密雙向操作。