• Stars
    star
    965
  • Rank 47,414 (Top 1.0 %)
  • Language
    Ruby
  • License
    MIT License
  • Created about 12 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A small Ruby gem to generate YouTube-like hashes from one or many numbers. Use hashids when you do not want to expose your database ids to the user.

Hashids

A small Ruby gem to generate YouTube-like ids from one or many numbers. Use hashids when you do not want to expose your database ids to the user.

http://hashids.org/ruby/

Build Status (push)

What is it?

hashids (Hash ID's) creates short, unique, decodable hashes from unsigned integers.

(NOTE: This is NOT a true cryptographic hash, since it is reversible)

It was designed for websites to use in URL shortening, tracking stuff, or making pages private (or at least unguessable).

This algorithm tries to satisfy the following requirements:

  1. Hashes must be unique and decodable.
  2. They should be able to contain more than one integer (so you can use them in complex or clustered systems).
  3. You should be able to specify minimum hash length.
  4. Hashes should not contain basic English curse words (since they are meant to appear in public places - like the URL).

Instead of showing items as 1, 2, or 3, you could show them as jR, k5, and l5. You don't have to store these hashes in the database, but can encode + decode on the fly.

All integers need to be greater than or equal to zero.

Installation

Add this line to your application's Gemfile:

gem 'hashids'

And then execute:

$ bundle

Or install it yourself as:

$ gem install hashids

Usage

Encoding one number

You can pass a unique salt value so your hashes differ from everyone else's. I use this is my salt as an example.

hashids = Hashids.new("this is my salt")
hash = hashids.encode(12345)

hash is now going to be:

NkK9

Decoding

Notice during decoding, same salt value is used:

hashids = Hashids.new("this is my salt")
numbers = hashids.decode("NkK9")

numbers is now going to be:

[ 12345 ]

Decoding with different salt

Decoding will not work if salt is changed:

hashids = Hashids.new("this is my pepper")
numbers = hashids.decode("NkK9")

numbers is now going to be:

[]

Encoding several numbers

hashids = Hashids.new("this is my salt")
hash = hashids.encode(683, 94108, 123, 5)

hash is now going to be:

aBMswoO2UB3Sj

Decoding is done the same way

hashids = Hashids.new("this is my salt")
numbers = hashids.decode("aBMswoO2UB3Sj")

numbers is now going to be:

[ 683, 94108, 123, 5 ]

Encoding and specifying minimum hash length

Here we encode integer 1, and set the minimum hash length to 8 (by default it's 0 -- meaning hashes will be the shortest possible length).

hashids = Hashids.new("this is my salt", 8)
hash = hashids.encode(1)

hash is now going to be:

gB0NV05e

Decoding with minimum hash length

hashids = Hashids.new("this is my salt", 8)
numbers = hashids.decode("gB0NV05e")

numbers is now going to be:

[ 1 ]

Specifying custom hash alphabet

Here we set the alphabet to consist of: "abcdefghijkABCDEFGHIJK12345"

hashids = Hashids.new("this is my salt", 0, "abcdefghijkABCDEFGHIJK12345")
hash = hashids.encode(1, 2, 3, 4, 5)

hash is now going to be:

dEc4iEHeF3

Randomness

The primary purpose of hashids is to obfuscate ids. It's not meant or tested to be used for security purposes or compression. Having said that, this algorithm does try to make these hashes unguessable and unpredictable:

Repeating numbers

hashids = Hashids.new("this is my salt")
hash = hashids.encode(5, 5, 5, 5)

You don't see any repeating patterns that might show there's 4 identical numbers in the hash:

1Wc8cwcE

Same with incremented numbers:

hashids = Hashids.new("this is my salt")
hash = hashids.encode(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

hash is now going to be:

kRHnurhptKcjIDTWC3sx

Incrementing number ids:

hashids = Hashids.new("this is my salt")

hashids.encode 1 #=> NV
hashids.encode 2 #=> 6m
hashids.encode 3 #=> yD
hashids.encode 4 #=> 2l
hashids.encode 5 #=> rD

Encoding using a HEX string

hashids = Hashids.new("this is my salt")
hash = hashids.encode_hex('DEADBEEF')

hash is now going to be:

kRNrpKlJ

Decoding to a HEX string

hashids = Hashids.new("this is my salt")
hex_str = hashids.decode_hex("kRNrpKlJ")

hex_str is now going to be:

DEADBEEF

Changelog

1.0.6

  • Fixed using lib with frozen strings
  • Remove deprecated global use of must_equal and must_raise
  • Use GitHub Actions instead of Travis-CI

1.0.5

  • Improve shuffle performance
  • Update rubies used by Travis-CI

1.0.4

  • Improved encode/decode performance

1.0.3

  • Support for Ruby 2.4.0

1.0.2

  • Handle invalid input by raising InputError

1.0.1

  • Final alphabet length can now be shorter than the minimum alphabet length
  • validate_alphabet now run before setting up seps & guards

1.0.0

  • Public functions renamed to be more appropriate:
  • encrypt changed to encode
  • encrypt_hex changed to encode_hex
  • decrypt changed to decode
  • decrypt_hex changed to decode_hex

0.3.0

  • Bumped the version number since hashids.rb now support the new algorithm
  • Support for encrypt_hex and decrypt_hex

0.0.3

  • Default salt (Allows for Hashids.new.encrypt(91) #=> "kBy")
  • Further tweaking of the private methods (tr/delete over gsub, scan over split)

0.0.2

  • Minitest required if RUBY_VERSION < 1.9.3
  • Using scan over split where appropriate

0.0.1

Contact

Follow me @peterhellberg

Or http://c7.se/

License

MIT License. See the LICENSE.txt file.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

More Repositories

1

wiki

A tiny wiki using BoltDB and Blackfriday
Go
203
star
2

xip.name

Simple wildcard DNS inspired by xip.io
Go
156
star
3

gfx

Convenience package for dealing with graphics in my pixel drawing experiments.
Go
124
star
4

karta

Experiments with map generation using Voronoi diagrams
Go
95
star
5

pixel-experiments

Various experiments using the pixel library
Go
87
star
6

pinch

Retrieve a file from inside a zip file, over the network!
Ruby
62
star
7

giphy

Go library for the Giphy API
Go
60
star
8

hiro

Generates HTML from API Blueprints using the Snow Crash command line tool Drafter and Iglo.
Go
53
star
9

tpb-search

Locally index and search database dumps from https://openbay.isohunt.to using the bleve text indexing library
Go
49
star
10

link

Parses Link headers used for pagination, as defined in RFC 5988
Go
40
star
11

go-streaming-loadbalancer

A small loadbalancer API written in Go (Using Pat, Redigo and Go-GeoIP)
Go
34
star
12

neocities

A Neocities client written in Go
Go
33
star
13

duration

Parse a RFC 3339 duration string into time.Duration
Go
29
star
14

swapi

A SWAPI client written in Go
Go
28
star
15

photography

Files used in my photography post processing workflow. Lightroom presets, etc.
25
star
16

dircolors-jellybeans

Dircolors suitable for use with jellybeans.vim
Shell
24
star
17

acr122u

A Go package for the ACR122U USB NFC Reader
Go
24
star
18

tinypng

A TinyPNG client written in Go
Go
22
star
19

sseclient

Server-sent events (SSE) client in Go
Go
19
star
20

hn

Go library for the Hacker News API
Go
19
star
21

flip

Go library used to flip text
Go
18
star
22

fixer

Go client for the Foreign exchange rates and currency conversion API 💰
Go
18
star
23

gopher

A simple server for the Gopher protocol written in Go.
Go
17
star
24

ssh-chat-bot

A small chatbot for ssh-chat
Go
17
star
25

lossypng

Library version of the lossypng command line tool by @foobaz
Go
16
star
26

env

Load environment variables into Go types, with fallback values.
Go
14
star
27

life

Conway's Game of Life written in Go using termbox-go
Go
12
star
28

dotfiles

My config files (aka dotfiles)
Vim Script
11
star
29

gui

Minimal GUI in Go initially based on https://github.com/faiface/gui
Go
11
star
30

emojilib

The Emoji keyword library by @muan ported to Go
Go
11
star
31

release

A small package used to parse scene release names
Go
9
star
32

nobel

Ruby client for the Nobel Prize API
Ruby
9
star
33

brandy

Brandy Basic V Interpreter patched to compile under OS X
C
9
star
34

w4-2048

2048 using the fantasy console WASM-4 and TinyGo
Go
8
star
35

wavefront

A go getable version of wavefront (OBJ/MTL) parser used by the go-qml examples.
Go
8
star
36

nesdev

I’m just playing around, not meant to be useful for anyone but me :)
Assembly
8
star
37

ruuvitag

This is a Go package for decoding RuuviTag sensor data
Go
7
star
38

gophereyes

A follow the mouse demo
Go
7
star
39

plasma

Experiments with plasma generation in Go
Go
6
star
40

adventure

A small text based adventure game using the ishell package.
Go
6
star
41

check-ssh-chat

Check if a ssh-chat server is up and responding
Go
5
star
42

jsonstore

A Go client for the www.jsonstore.io API   💾 🚀
Go
5
star
43

population

Go library for the World Population API
Go
4
star
44

natsdraw

draw.Image over NATS
Go
4
star
45

go-pinch

Pinch using Go
Go
4
star
46

maze

Generate a maze using Prim's Algorithm
Go
4
star
47

loc

SSE stream of visitor locations plotted on a map using D3.js
Go
4
star
48

hi

Find images for a given hashtag
Go
3
star
49

beats

Go library for all your Swatch Internet Time needs
Go
3
star
50

publicdns

A client for Google Public DNS written in Go
Go
3
star
51

hackerrank

Solutions to HackerRank challenges.
Go
2
star
52

vedis-from-c-and-go

Experimenting with Vedis from C and Go
C
2
star
53

lights

A command line tool for circadian lighting at my desk
Go
2
star
54

humans

Parsing your humans.txt into JSON
Ruby
2
star
55

microview

Go library used to remote control a MicroView
Go
2
star
56

go-tdtool-api

A simple API in front of the TellStick tdtool written in Go (List and turn devices on/off)
Go
2
star
57

mandelbrot

The Mandelbrot Set in Go
Go
2
star
58

monastic

Implementation of The Ciphers of the Monks in Go
Go
2
star
59

kinetosis

Read XYZ orientation data from the Sudden Motion Sensor present in most recent Apple laptops. (This is a lie since the Air doesn’t even have one… so I don’t have a way to keep the code updated :)
Ruby
2
star
60

mat

A small API client for the Mat API
Ruby
1
star
61

scb

A small API client for the SCB API.
Ruby
1
star
62

peterhellberg.github.com

My Open Source projects on GitHub
1
star
63

nostr-json

Generate a nostr.json used for verification of a Nostr user
Go
1
star
64

fuzz

Randomized testing for my Go packages using go-fuzz
Go
1
star
65

stub-web-server

Stub web server used for testing
Go
1
star
66

sr

Go library for Sveriges Radio API
Go
1
star
67

brickcolor

A (generated) Go package with all of the Roblox BrickColor Codes
Go
1
star
68

land_of_lisp

A series of Lisp exercises as I work through the Land of Lisp book
Common Lisp
1
star
69

riksteatern

Ruby client for the Riksteatern API
Ruby
1
star
70

langtons-ant

Langton's ant written in Go using termbox-go
Go
1
star
71

typ

A small Zig âš¡ module, as a convenience for me when writing WebAssembly plugins for Typst
Zig
1
star
72

filmtipset

API client for the Filmtipset API (requires access key)
Ruby
1
star
73

code_year

EXPERIMENT: A VERY naïve parser for the #code2011 tweets
Ruby
1
star
74

gradient

Create vertical and horizontal gradients in Go
Go
1
star
75

warmup

HTTP cache warming
Go
1
star