Cryptographic hash functions are better than manual hashing

Cryptographic hash functions are better than manual hashing

Table of contents

Cryptographic hash functions like SHA-256 and MD5 are designed to be more uniform and secure compared to simple manual hashing techniques using ASCII values.

Here is why:

  1. Uniformity: Cryptographic hash functions spread out hash values evenly. This means small changes in the input create very different hash values, reducing the chance of overlap and collisions. On the other hand, hashing by hand with ASCII values can cause uneven distribution and more collisions.

  2. Avalanche effect: Cryptographic hash functions have the avalanche effect, meaning a tiny change in the input (like changing just one bit) leads to a big change in the output hash. This makes sure that even similar inputs end up with very different hash values, improving how they spread out and making the output hard to guess.

  3. Efficiency: Cryptographic hash functions are made to work quickly and efficiently. They can create hash values for big data sets fast, making them good for hash tables and other structures that often need hashing.

  4. Security: Cryptographic hash functions are made to work in one direction and avoid duplicates. It's nearly impossible to figure out the original input from the hash or find two different inputs that give the same hash. While not all hashing needs this high security, it offers extra protection against attacks.

Example

Let's take a look at an example where we create a pure function that takes a string and an array of values.

Our goal is to turn the string into an index.

const crypto = require('crypto');

function hashFunction(key, array) {
  const hash = crypto.createHash('sha256').update(key).digest('hex');
  const index = parseInt(hash, 16) % array.length;
  return array[index];
}

// Example usage
const myArray = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

// Returns a value from myArray
const value1 = hashFunction('hello', myArray);

// Returns a different value from myArray
const value2 = hashFunction('world', myArray);

In this example, the SHA-256 hash of the input string is computed, and then the modulo operator is applied to the hash value to map it to an index within the range of the array. The resulting index is used to retrieve the corresponding value from the array.

Conclusion

By leveraging the uniformity and avalanche effect of SHA-256, you can achieve better distribution and reduce the likelihood of collisions compared to manual hashing techniques.