Hashids
Hashids is a small library that generates short, unique, and non-sequential IDs from numbers. It's often used for obfuscating database IDs in URLs, tracking, or invitation codes, providing a user-friendly and URL-safe representation of integers without exposing their underlying numeric values. The current version is 1.3.1. It is mostly in maintenance mode, as a new version called Sqids is the recommended successor.
Warnings
- gotcha Hashids is for obfuscation, not security or cryptography. It is reversible and should not be used for sensitive data, passwords, or any scenario requiring true cryptographic hashing.
- breaking The default alphabet was changed in versions 1.0.0 and above. If you need compatibility with hashids.js v0.1.x, you must install hashids-python v0.8.4. For hashids.js v0.3.x+, use hashids-python v1.0.2+.
- gotcha Using a unique `salt` value is crucial. Without a salt (or with a commonly known one), different applications would generate the same hash for the same number, making it easy to guess or reverse.
- deprecated The original creator of Hashids has introduced an improved and rebranded library called 'Sqids'. While Hashids is still maintained, Sqids is the recommended successor for new projects, offering a simplified API, consistent output across languages, and clearer goals.
- gotcha Hashids does not prevent enumeration attacks on its own. While it obfuscates sequential IDs, if an attacker can simply increment/decrement the generated hash and get valid responses, it can still expose the total number of records or allow unauthorized access if not backed by proper authorization.
Install
-
pip install hashids
Imports
- Hashids
from hashids import Hashids
Quickstart
from hashids import Hashids
# Instantiate with optional salt and minimum hash length for better obfuscation
# Using a salt makes your hashes unique to your application.
# min_length ensures all generated hashes are at least that long.
# For production, consider getting the salt from environment variables.
hashids = Hashids(salt="my-super-secret-salt-from-env", min_length=8)
# Encode one or more integers into a hashid string
id_to_encode = 12345
encoded_id = hashids.encode(id_to_encode)
print(f"Encoded {id_to_encode}: {encoded_id}")
multiple_ids_to_encode = (1, 2, 3)
encoded_multiple = hashids.encode(*multiple_ids_to_encode)
print(f"Encoded {multiple_ids_to_encode}: {encoded_multiple}")
# Decode a hashid string back to its original integers (as a tuple)
decoded_ints = hashids.decode(encoded_id)
print(f"Decoded '{encoded_id}': {decoded_ints}")
decoded_multiple = hashids.decode(encoded_multiple)
print(f"Decoded '{encoded_multiple}': {decoded_multiple}")