hashids

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package hashids is a standard-library port of the Hashids algorithm (https://hashids.org), mirroring the popular npm "hashids" package. It encodes slices of non-negative integers into short, reversible, non-sequential strings using a salt, a configurable minimum length and a custom alphabet. Typical uses include obfuscating database identifiers in URLs and generating opaque, YouTube-style public IDs that do not leak the underlying sequential values.

Hashids first appeared as a JavaScript library in 2012 and was created to solve a common web problem: exposing raw auto-increment primary keys in public URLs reveals how many records exist and invites enumeration. Hashids deliberately is not encryption; it is a reversible obfuscation that keeps output compact and URL-safe while making adjacent identifiers look unrelated. This port keeps the same design goals and, given the same salt and alphabet, produces byte-for-byte the same output as the reference JavaScript implementation, so IDs generated by one can be decoded by the other.

Encoding works by deriving a per-call "lottery" character from the input numbers, then repeatedly applying a deterministic "consistent shuffle" of the alphabet that is seeded by the salt, the lottery and the current alphabet. Each number is written in the shuffled alphabet's base, individual numbers are joined with separator characters, and, when a minimum length is requested, guard characters and shuffled padding are added symmetrically around the payload until the length is satisfied. The alphabet is split into three disjoint roles up front: the working alphabet used to render digits, a set of separators (drawn from "cfhistuCFHISTU" intersected with the alphabet), and a small set of guard characters, which is what lets Decode reliably re-split a hash.

Construct a codec with New, which uses DefaultAlphabet, or with NewWithAlphabet to supply your own. The alphabet is deduplicated while preserving order and must contain at least 16 unique characters and no spaces; otherwise construction returns an error. The minimum length is clamped to zero if negative. Encode accepts any number of non-negative int64 values: encoding no numbers returns the empty string, and encoding a negative number returns an error, since Hashids only models non-negative integers. Decode is the inverse and validates its result by re-encoding and comparing; input that does not decode consistently (including the empty string and strings containing characters outside the alphabet) yields an empty slice with a nil error rather than a hard failure.

Parity with the Node package is intentional but scoped: this port covers the core integer Encode and Decode paths, the salt, custom alphabet and minimum-length options, and matches the project's official test vectors (for example {12345} encodes to "NkK9" under the salt "this is my salt"). It does not implement the hex-string helpers (encodeHex/decodeHex) offered by some Hashids libraries. Note that Hashids is not a security primitive: the salt only diversifies output and can be recovered from enough samples, so never rely on it to hide sensitive data.

Index

Examples

Constants

View Source
const (
	// DefaultAlphabet is the alphabet used when none is supplied.
	DefaultAlphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type HashID

type HashID struct {
	// contains filtered or unexported fields
}

HashID encodes and decodes integer slices.

func New

func New(salt string, minLength int) (*HashID, error)

New returns a HashID using the default alphabet.

func NewWithAlphabet

func NewWithAlphabet(salt string, minLength int, alphabet string) (*HashID, error)

NewWithAlphabet returns a HashID using a custom alphabet.

func (*HashID) Decode

func (h *HashID) Decode(hash string) ([]int64, error)

Decode decodes a hash back into the integers it encodes. It returns an empty slice for input that does not decode consistently.

Example

ExampleHashID_Decode demonstrates the inverse of Encode, recovering the original integers from a hash. Decode uses the same salt and alphabet that produced the hash and validates its work by re-encoding the result. Multiple numbers can be encoded together and are returned in the same order. This example round-trips the slice {1, 2, 3}, which encodes to "laHquq" under the sample salt, back to its original values. A hash that does not decode consistently would instead yield an empty slice.

package main

import (
	"fmt"
	"log"

	"github.com/malcolmston/express/hashids"
)

func main() {
	h, err := hashids.New("this is my salt", 0)
	if err != nil {
		log.Fatal(err)
	}
	hash, err := h.Encode(1, 2, 3)
	if err != nil {
		log.Fatal(err)
	}
	nums, err := h.Decode(hash)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(hash)
	fmt.Println(nums)
}
Output:
laHquq
[1 2 3]

func (*HashID) Encode

func (h *HashID) Encode(nums ...int64) (string, error)

Encode encodes the given non-negative integers.

Example

ExampleHashID_Encode shows how to turn a single non-negative integer into a short, non-sequential hash. A codec is created with a salt, which diversifies the output so that the same numbers produce different hashes under different salts. The minimum length of 0 means no padding is added and the hash is as short as the algorithm allows. Encoding is deterministic: the same salt, alphabet and numbers always yield the same string. Here the salt "this is my salt" encodes 12345 to the canonical Hashids value "NkK9".

package main

import (
	"fmt"
	"log"

	"github.com/malcolmston/express/hashids"
)

func main() {
	h, err := hashids.New("this is my salt", 0)
	if err != nil {
		log.Fatal(err)
	}
	hash, err := h.Encode(12345)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(hash)
}
Output:
NkK9

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL