✖

Hash function (hash)

A hash function turns data of any length into a short fingerprint of fixed length, called a hash (or hash value), hence the name: the same data always gives the same hash, slightly different data gives a completely different one, and there is no way to get from the hash back to the data. That is how a website can recognise your password even though it has not stored it anywhere. At registration it keeps only the password’s hash. At login it computes the hash of what you typed and compares the two. A hash is also useful after downloading a program: it lets you tell that nobody has slipped you a different file on the way.

Three inputs of different lengths, the letter a, the word abc and a million letters a in a row, go into the SHA-256 function. Each produces a red hash of 64 characters, and each time it is completely different Three inputs of different lengths, the letter a, the word abc and a million letters a in a row, go into the SHA-256 function. Each produces a red hash of 64 characters, and each time it is completely different

The most widely used hash function is called SHA-256. Whether you feed it one letter or a million letters, the hash always has 64 characters.

A toy example: the sum of letters

Let’s build a hash function of our own. We replace each letter with its position in the alphabet, so A is 1, B is 2, and so on up to Z, which is 26, and we ignore diacritics (the little hooks and accents). This is called a number cipher. We add up the numbers and declare the remainder after dividing by 100 to be the hash. So the result is a number from 0 to 99.

The word “Eva” gives 5 + 22 + 1 = 28. A hundred does not go into 28 even once, so the whole 28 is left as the remainder, and that is our hash. Now a longer word, “kryptografie” (Czech for “cryptography”):

11+18+25+16+20+15+7+18+1+6+9+5=151

A hundred goes into 151 once, leaving 51. The hash of the word “kryptografie” is 51. The long word has given a hash just as short as the short one.

The toy already manages two things. The same word always gives the same hash. And you cannot work out the word from the hash: when adding, we lose which letters there were and in what order.

But it is easy to find another word with hash 51, for example “jablko” (apple), because 10 + 1 + 2 + 12 + 11 + 15 = 51. We have found a collision: two different pieces of data with the same hash. For the toy, that is the end. If a website remembered the hash of the password “kryptografie”, it would let in anyone who typed “jablko”. Collisions can also be found with no thought at all: “kos” (blackbird) and “sok” (rival) have the same letters, so they have the same sum, 45.

No hash function can avoid collisions, though, not even the best one. There are only a hundred hashes, but far more words. Take 101 different words and at least two of them end up with the same hash, just as when you sort 101 letters into a hundred pigeonholes: some pigeonhole must hold two. The only difference is that with a good hash function, nobody can find a collision.

What a good hash function must do

  • One way only. Given a hash, the only way to find data that produces it is blind guessing.
  • Nobody can find collisions. They exist, but nobody can produce two different pieces of data with the same hash.
  • Avalanche effect. Changing a single character of the input is enough to change the whole hash, not just a piece of it.

Our toy fails on every count: we found a collision in no time, and if you swap the E in “Eva” for an F, the hash only goes up by one.

The SHA-256 hash

A SHA-256 hash has 256 bits. A bit is a single zero or one, so the hash is a row of 256 zeros and ones. Writing out such a row would be awkward, so it is written in hexadecimal: with the digits 0 to 9 and the letters a to f, which stand for the values 10 to 15. A group of four zeros and ones has 2 · 2 · 2 · 2 = 16 possibilities, exactly as many as there are of these characters, so one character stands for four bits: 1010 is a, 1111 is f. So 256 bits become 64 characters.

Let’s try two sentences that differ in a single character: “Adam owes Bára £100.” and “Adam owes Bára £900.” The hash of the first begins b2b62bba, and the hash of the second 4d2187bf. In the picture, each square stands for one bit: blue is a one, grey a zero. At the bottom, the bits that changed between the hashes light up in red.

At the top, the hash of the sentence Adam owes Bára £100 and below it its 256 bits in a grid, a blue square is a one, a grey one a zero. In the middle the same for the sentence with £900. At the bottom, in red, the bits that changed: 124 out of 256 At the top, the hash of the sentence Adam owes Bára £100 and below it its 256 bits in a grid, a blue square is a one, a grey one a zero. In the middle the same for the sentence with £900. At the bottom, in red, the bits that changed: 124 out of 256

A single digit flipped 124 of the 256 bits, roughly half, and that is exactly what we want from a good hash function: each bit changes or stays the same as if decided by a coin toss. Of the 64 characters of the written form, only 6 stayed in their place. Looking at the hashes, you would never guess that the sentences are almost the same. But anyone who has kept the hash of the original sentence will spot any change, even a single digit.

How many different hashes are there? Each of the 256 places is filled with a zero or a one, so there are 2256 possibilities in total. That is a number with 78 digits:

2256≈1.16⋅1077

The number of atoms in the entire observable universe is estimated at about 1080, so only about a thousand times more than the number of possible hashes. Anyone who wants to find data for a given hash has to guess, and needs on the order of 2256 attempts to do so.

The birthday paradox

Finding a collision, that is, any two different pieces of data with the same hash, is much easier. An old puzzle shows this: how many people must be in a class for two of them to share a birthday with a probability of at least 50%? Most people guess around 183, half of 365. In fact 23 are enough.

The catch is that we are not looking for someone who shares a birthday with me, but for any pair. And among 23 people there are a lot of pairs:

23⋅222=253

Each pair is one chance of a match. Among n people there are roughly n2/2 pairs, so their number grows much faster than the number of people. Once there are about as many pairs as days in the year, a match is more likely than not. The easiest way to calculate it is through the opposite: the second person must avoid one day, the third two days, and so on up to the twenty-third. The probability that no birthdays coincide is

364365⋅363365⋯343365≈0.493,

so a match happens with probability 1 − 0.493 = 0.507, that is, 50.7%.

A graph of the probability that among n people two share a birthday, for 1 to 60 people. The red curve rises, the orange point at 23 people lies just above 50%, and at 60 people it is over 99% A graph of the probability that among n people two share a birthday, for 1 to 60 people. The red curve rises, the orange point at 23 people lies just above 50%, and at 60 people it is over 99%

That is why a match arrives at roughly the square root of the number of possibilities: 365≈19, which is the same order of magnitude as 23. For our toy with a hundred hashes, 13 words with random hashes would be enough for a collision to be more likely than not. For SHA-256 the square root gives

2256=2128.

That is incomparably less than 2256, and yet still unreachably many. Even if a billion computers each tried a billion hashes per second, searching for a collision would take them roughly eight hundred times longer than the universe has existed.

Password hashes and salt

A decent website does not store your password, only its hash. So when someone steals the database, which happens all the time, all they get are hashes, from which the passwords cannot be worked out.

But an attacker can do the same as the website. They take millions of the most popular passwords, such as 123456, password or Password1, compute their hashes and look for a match in the stolen database. This is called a dictionary attack. What is more, the hashes of popular passwords only need to be computed once in advance and stored, most often in a compact form called rainbow tables. Anyone who has chosen the password “password” is exposed at once, however good the hash function.

The remedy is salt: a random string that the website generates for each user, attaches to the password and only then computes the hash. The salt sits in the database right next to the hash and is not secret. But Adam and Bára, who both have the password “password”, end up with completely different hashes because of their different salts, and precomputed tables are useless. The attacker has to guess separately for each user.

For passwords, deliberately slow functions are used, such as bcrypt or Argon2. A fraction of a second at login does not bother you, but for an attacker who would otherwise try billions of passwords per second, it slows the work down many times over.

Practical advice for you: a long password that is in no dictionary, and a different one on every website. A password manager does this most conveniently. How many guesses each password withstands is worked out in the article on password security.

Checking a downloaded file

Websites offering programs to download often list a SHA-256 hash next to the link. Compute the hash of the downloaded file and compare. A difference in a single character and you have a different file. But the hash only helps if you get it from somewhere other than the file: anyone who took over the whole website would swap both. On Windows, type certutil -hashfile file.iso SHA256 at the command prompt, on a Mac type shasum -a 256 file.iso in Terminal, and on Linux sha256sum file.iso.

Bitcoin

Bitcoin mining is a search for a hash. Bitcoin records payments in blocks, bundles of payments, and wants adding a new block to take many attempts so that nobody can easily rewrite the payment history. So a miner adds a number to the block and computes the SHA-256 hash. If the hash does not come out small enough, that is, does not begin with a long enough run of zeros, they try the next number, and so on, over and over. Whoever finds a suitable number first gets a reward. The search takes an enormous number of attempts, while checking takes a single hash computation, so everyone else can easily verify that the miner did not cheat.

When a hash function falls

Nobody has proved that a hash function is secure. We trust it until someone finds a shortcut. For two famous functions, someone did.

MD5, with a hash of 128 bits, was used everywhere in the 1990s. In August 2004 a Chinese team led by Wang Xiaoyun published the first MD5 collisions, exactly what nobody was supposed to manage. In December 2008 a group of cryptographers led by Alexander Sotirov and Marc Stevens showed at the 25C3 conference in Berlin what could be done with that. A certificate is a website’s “ID card”, vouched for by a trusted company, a certificate authority, which signs its hash. The researchers had an ordinary certificate signed by the authority RapidSSL and had prepared in advance a second one with the same MD5 hash, so the signature was valid for the second one too. The second certificate thus turned them into a rogue certificate authority, trusted by all the common browsers, which could issue a certificate for any website. The computation took roughly 200 PlayStation 3 game consoles.

The stronger SHA-1, with a hash of 160 bits, lasted longer. On 23 February 2017, Google and the CWI institute in Amsterdam announced the first SHA-1 collision, called SHAttered: two different PDF files with the same hash. It took roughly nine quintillion SHA-1 computations, about 6,500 years of processor work and 110 years of graphics card work. For an individual that is too much, but for a large company or a state it is a feasible task.

SHA-256 was published by the US standards body NIST in 2001 in the draft of the FIPS 180-2 standard. Nobody has found a collision for it so far, and attacks succeed only against reduced versions with fewer rounds.

What about a quantum computer?

Shor’s algorithm would break RSA, Diffie–Hellman and elliptic curves on a quantum computer. But hash functions are not threatened by a quantum computer. Grover’s algorithm only speeds up the search from N attempts to roughly N, for SHA-256 to 2128, and that is still unreachable. One of the new post-quantum signatures, SLH-DSA, is also built on hash functions.

See also