AlgoTales · Roadmap

Hash functions

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A hash function turns any input, like a name, email or file, into a fixed-size number. The same input always gives the same number, and different inputs usually give different numbers. This makes quick lookups, fingerprints and spreading of load possible.

Practical use cases

  • Web app: Checking a downloaded file is intact. A software download page shows a checksum next to the file. After downloading, the user computes the file's fingerprint and compares it. If one byte changed, the number is totally different, so a corrupted or tampered file is caught in seconds.
  • Web app: Safe password storage. A login system never keeps real passwords. It stores the hash of each password with a random salt, and at login hashes what was typed and compares. If the user table leaks, attackers get fingerprints, not passwords, and a good slow hash makes guessing very costly.
  • System: Hash tables and load balancers. Language dictionaries and PHP arrays use hash functions to decide where each key is stored. Load balancers hash a user id to choose a server, so the same user keeps landing on the same machine and caches stay useful, and the load spreads fairly evenly across all servers.

The story: The Magic Locker Keeper

Gandhi Memorial School had 200 students and only 10 old lockers in the corridor. Every morning Mr. Verma, the peon, had to find each child's locker: he walked down the row and checked the name tag on each one. On busy days, Kabir waited so long that he missed the assembly.

Mrs. Sharma came up with a trick. "Mr. Verma, do not search. Use a little recipe on the child's name: take each letter's number, mix it into a running total, and keep only the last digit. That digit is the locker." Raju's name gave locker 8, every single day. Nobody had to remember anything and nobody had to search.

Mira asked, "What if the recipe gives a different answer every day?" Mrs. Sharma smiled. "Then it is useless. A good recipe always gives the same answer for the same name, is quick to do, and spreads children across all the lockers instead of piling them into one." That recipe is a hash function: it turns any key into a number in a fixed range.

How to spot this problem, and where you need it

You need to turn long or awkward data into a small, repeatable number to compare things quickly, find where to store them, check they were not changed, or keep secrets out of storage.

Signs you need it

  • You compare big files, long texts or whole records just to find out if they are identical or have changed.
  • You need a quick key to decide which bucket, shard, server or cache slot an item should go to.
  • You store sensitive data such as passwords and only need to check a match later, never read the original back.

Where to use it in a project

  • Password storage and file integrity checks in login and download features.
  • Cache keys, shard selection and load-balancing by user id or session.
  • Detecting changed or duplicate content in sync, backup and import tools.

The solution

Pick a well-tested hash function for the job: a fast one for lookups and checksums, a slow, salted one (such as bcrypt or Argon2) for passwords. Feed the data in, take the resulting number or code, and use it as the key, the fingerprint or the stored value. Never invent your own function for security work.

Payoff: Before: comparing a 2 GB file byte by byte or storing real passwords. After: comparing two short fingerprints, and a leaked table reveals no passwords.

Explain it like I am 8

A hash function is like a machine that turns your name into a house number. Put the same name in tomorrow and the same number comes out. The machine is quick, and it tries to send different names to different houses.

How it works, step by step

  1. Start with a running value of 0.
  2. For each letter of the key: multiply the running value by a small prime-like number such as 31, then add the letter's code. (This "mixing" makes RAJU and JURA land in different places.)
  3. After each letter, keep only the remainder after dividing by the number of lockers (% size), so the value never gets huge.
  4. The final remainder is the locker (bucket) number, always between 0 and size - 1.
  5. A good hash function is deterministic (same input, same output), fast, and spreads keys evenly.

The code in four languages

PHP

<?php
// A tiny string hash: mix each letter into a running value, keep it within 0..size-1.
function hashKey(string $key, int $size): int {
    $h = 0;
    for ($i = 0; $i < strlen($key); $i++) {
        $h = ($h * 31 + ord($key[$i])) % $size;   // multiply, add the letter's code, wrap
    }
    return $h;
}

$lockers = 10;
foreach (['RAJU', 'MIRA', 'KABIR', 'ZOYA'] as $name) {
    echo $name . ' -> locker ' . hashKey($name, $lockers) . "\n";
}
// Same input always gives the same output:
echo (hashKey('RAJU', $lockers) === hashKey('RAJU', $lockers) ? 'same' : 'different') . "\n";

JavaScript

// A tiny string hash: mix each letter into a running value, keep it within 0..size-1.
function hashKey(key, size) {
  let h = 0;
  for (let i = 0; i < key.length; i++) {
    h = (h * 31 + key.charCodeAt(i)) % size;   // multiply, add the letter's code, wrap
  }
  return h;
}

const lockers = 10;
for (const name of ['RAJU', 'MIRA', 'KABIR', 'ZOYA']) {
  console.log(name + ' -> locker ' + hashKey(name, lockers));
}
// Same input always gives the same output:
console.log(hashKey('RAJU', lockers) === hashKey('RAJU', lockers) ? 'same' : 'different');

Java

public class Main {
    // A tiny string hash: mix each letter into a running value, keep it within 0..size-1.
    static int hashKey(String key, int size) {
        int h = 0;
        for (int i = 0; i < key.length(); i++) {
            h = (h * 31 + key.charAt(i)) % size;   // multiply, add the letter's code, wrap
        }
        return h;
    }

    public static void main(String[] args) {
        int lockers = 10;
        for (String name : new String[]{"RAJU", "MIRA", "KABIR", "ZOYA"}) {
            System.out.println(name + " -> locker " + hashKey(name, lockers));
        }
        // Same input always gives the same output:
        System.out.println(hashKey("RAJU", lockers) == hashKey("RAJU", lockers) ? "same" : "different");
    }
}

Go

package main

import "fmt"

// hashKey is a tiny string hash: mix each letter into a running value, keep it within 0..size-1.
func hashKey(key string, size int) int {
	h := 0
	for i := 0; i < len(key); i++ {
		h = (h*31 + int(key[i])) % size // multiply, add the letter's code, wrap
	}
	return h
}

func main() {
	lockers := 10
	for _, name := range []string{"RAJU", "MIRA", "KABIR", "ZOYA"} {
		fmt.Println(name, "-> locker", hashKey(name, lockers))
	}
	// Same input always gives the same output:
	if hashKey("RAJU", lockers) == hashKey("RAJU", lockers) {
		fmt.Println("same")
	} else {
		fmt.Println("different")
	}
}

Time: O(k) · Extra space: O(1). The work grows with the key's length k (one step per letter), and for short keys that is practically instant.

Watch out for

  • Using something random or changing (like the current time) inside the hash. The same key must always give the same number.
  • Forgetting that two different keys can land on the same number. That is normal and is handled by collision strategies.
  • Using a hash made for passwords (slow and secure) inside a hash table, or a quick table hash for passwords. They are for different jobs.

Quick check

  1. What must a hash function give for the same key every time?
    • A random number
    • The same number
    • A bigger number
  2. Why do we use the remainder (%) at the end?
    • To keep the number inside the table size
    • To make the key shorter
    • To sort the keys
  3. Can two different keys get the same hash value?
    • Never
    • Yes, it is called a collision
    • Only numbers can