code q&a
Resources About
Question:

What is a hash?

A hash is a short string of letters and numbers calculated from a piece of data, like a word, a password or a whole movie file. A hash function does the calculating and always gives the same hash for the same input.

Here’s what SHA-256, a popular hash function, gives for two almost identical inputs:

hello   2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
hello!  ce06092fb948d9ffac7d1a376e404b26b7575bcc11ee05a4615fef4fec3a308b

Adding one exclamation point changes the entire hash. Both outputs are exactly 64 characters long because every SHA-256 hash is that length.

Hashing only works in one direction, so you can’t turn a hash back into the original data. That’s the big difference from encryption, where anyone with the right key can unlock the data. Two different inputs that produce the same hash cause what’s called a collision. Good hash functions make collisions extremely rare. MD5 is an old hash function that’s considered broken for security because attackers can create collisions on purpose. Most security tools use SHA-256 instead.

Developers run into hashes all the time. Websites store a hash of your password instead of the password itself, so a leaked database doesn’t expose everyone’s real passwords. Password hashing functions like bcrypt are deliberately slow so attackers can’t test billions of guesses per second. Every commit in Git gets an ID that’s a hash of the commit’s contents. Download pages often list a file’s SHA-256 hash so you can check it in your terminal and confirm the file wasn’t corrupted or tampered with.

Hash tables, also called hash maps or dictionaries, use hashes to find values fast. The hash of a key tells the program exactly where to look, so it never has to search through every item. Python dictionaries and JavaScript Map objects work this way. The word “hash” sometimes just means a hash table, like in Ruby where dictionaries are called Hash.

You might also like