Hashing

What Is a Hash Function in Hashing?

A hash function turns input of any size into a fixed-size value. The same input gives the same output. Learn the basic properties and see a simple example.

On this page
  1. The short answer
  2. A simple example
  3. Properties of a good hash function
  4. Cryptographic and non-cryptographic hash functions
  5. Where hash functions are used
  6. Summary

The short answer

A hash function takes input of any size, such as a word, a file or a number, and returns a fixed-size value. That value is called a hash, a hash code or a digest. The same input always gives the same output.

A simple example

Here is a toy hash function for teaching. Give each letter its place in the alphabet, with a = 1 up to z = 26. Add the numbers together, then take the remainder after dividing by 10. That gives a slot from 0 to 9.

  • “cat”: 3 + 1 + 20 = 24. The remainder after dividing 24 by 10 is 4, so “cat” goes to slot 4.
  • “act”: the same letters in a different order give the same total, 24, so “act” also goes to slot 4.

Those two words collide. Real hash functions are designed to avoid easy patterns like this one, but the example shows what a collision is.

Properties of a good hash function

  • Deterministic. The same input always gives the same output.
  • Fixed-size output. A short word and a large file both produce a value of the same length.
  • Even spread. Outputs are spread fairly evenly, which helps hash tables and data placement.
  • Collisions can happen. There are more possible inputs than outputs, so some different inputs must share a hash. Good functions make collisions uncommon in practice.

Cryptographic and non-cryptographic hash functions

Some hash functions are also built to resist attack. Cryptographic ones are designed so that it is hard to find an input that produces a given output, and hard to find two inputs with the same output. A small change to the input should also change the output a lot. Non-cryptographic functions drop these goals in exchange for speed.

Where hash functions are used

Hash functions appear in hash tables, checksums, digital signatures and data placement. The consistent hashing algorithm, for example, uses a hash function to place servers and keys on a ring. For the most common everyday use, see what is the main use of hashing.

Summary

A hash function maps input of any size to a fixed-size value. The same input gives the same output, the outputs spread fairly evenly, and different inputs can occasionally share a value.

The complete guide to hashing

How the Consistent Hashing Algorithm Works
Read the guide

Keep exploring

Guides from other topics

All topics →