HASHING: A Simple Developer's Guide

Hashing for Data Integrity and Security with bcryptjs in Nodejs.

HASHING: A Simple Developer's Guide

Hello readers! As a developer, you often encounter the term "hashing" in the world of computer science and cybersecurity. It's an essential concept that plays a significant role in ensuring data security and integrity. Let's explore an interesting adventure into the "Hashing" universe, by explaining it in the simplest way possible, without diving too deep into complex technical jargon.

What is Hashing?

Think of Hashing as a process of generating a unique digital fingerprint for a piece of data whether it’s a file, password or dialog, just like every individual human has its unique fingerprint. The term "hash value" or "hash" is used to describe this fingerprint.

Elaborately, hashing is the process of transforming a sequence of characters that represent text called “String” into another value of a fixed length of the longer or shorter value of alphanumeric characters called “hash value”.

Example of hash value:

{
    _id: 64be526815dc7b2dd8c3c9e8
    name: "john Doe"
    email: "johnDoe@gmail.com"
    password: "$2a$10$Wm82sAh6adybzfO4IHgdMOQwvSv67SsUGktdyLhtgNUfya0Vc5hJS"//hash value of a password
    __v:0
}

How Does Hashing Work?

Hashing uses a special function called a "hash function." When you input some data into a hash function, it performs a series of calculations on that data and produces a fixed-size output, which is the hash value.

Here are the steps to hash using bcryptjs in Node.js:

Step 1: Install bcryptjs First, you need to install the bcryptjs package. Open your terminal or command prompt and navigate to your Node.js project directory. Then, run the following command:

npm install bcryptjs

Step 2: Require bcryptjs In your Node.js file where you want to use bcrypt for hashing, require the bcryptjs package:

const bcrypt = require('bcryptjs');

Step 3: Generate a Salt A "salt" is random data that is generated and used as an additional input to the hash function, making the hashing process more secure. Use bcrypt.genSalt() to generate a salt. The genSalt() function takes an optional parameter, the number of salt rounds (higher rounds are more secure but slower to compute). For example, with 10 rounds:

const saltRounds = 10;

bcrypt.genSalt(saltRounds, function(err, salt) {
  if (err) {
    // Handle error
  } else {
    // Use the generated salt to hash the data
  }
});

Step 4: Hash the Data Once you have the salt, you can use it along with the data you want to hash. The data can be a password, user information, or any sensitive information you want to protect. Use bcrypt.hash() to create the hash:

const dataToHash = 'sensitive_data';

bcrypt.genSalt(saltRounds, function(err, salt) {
  if (err) {
    // Handle error
  } else {
    bcrypt.hash(dataToHash, salt, function(err, hash) {
      if (err) {
        // Handle error
      } else {
        // The 'hash' variable now contains the hashed value of 'dataToHash'
        console.log('Hashed data:', hash);
      }
    });
  }
});

Step 5: Compare Hashed Data (Optional) Later, when you want to check if a given input matches the stored hashed data (e.g., during login), you can use bcrypt.compare():

const input = 'user_input'; // Input data you want to compare

bcrypt.compare(input, hash, function(err, result) {
  if (err) {
    // Handle error
  } else if (result === true) {
    // The input matches the hash
    console.log('Input matches the hash!');
  } else {
    // The input does not match the hash
    console.log('Input does not match the hash.');
  }
});

That's it! You've successfully hashed data using bcryptjs in Node.js. Remember that bcrypt is designed to be slow and computationally intensive, which adds an extra layer of security against brute-force attacks.

Here's the fascinating part: Even the smallest change in the input data will completely change the hash value. For example, adding a single character or a tiny bit of data will create an entirely different hash.

Why is Hashing Important?

Hashing has evolved significantly ranging from application to the basic data integrity checks to advanced cryptographic protocols, helping to safeguard sensitive information and ensure the confidentiality, integrity, and authenticity of data in the digital age. As technology continues to advance, the importance of robust hashing mechanisms and secure cryptographic practices will remain paramount in ensuring data security.

Hashing is crucial for data security and integrity. Here's why:

1. Password Security: The system does not save your real password when you register an online account or when you generate a password. Instead, it encrypts it with a hash and retains the hash value. The system checks the entered password's hash to a previously saved one when you log in. You're given access if they match up.

2. Data Integrity: Hashing helps ensure data consistency. The website frequently offers a hash value for each file you download. After downloading, you can hash the file yourself and be sure that the file has been preserved and unaltered if the hash matches the one that was provided.

3. Digital Signatures: Hashing plays a role in digital signatures, where someone "signs" a document or message using their private key. The signature is a hash of the file that has been encrypted with the signer's private key. By decrypting the signature with the sender's public key and then comparing it to the document's hash, third parties can verify the validity of the document.

There are many hash functions out there, but some popular ones you might encounter are MD5, SHA-1, SHA-256, and SHA-3. SHA-256 is currently widely used due to its strong security properties.

Final Thoughts

Developers employ the straightforward yet effective technique of hashing to enhance security and guarantee data security. Keep in mind that even tiny alterations in the data might produce a unique hash. The next time you encounter hashing while learning to code, you'll understand it's all about assigning data a distinctive digital fingerprint to render the internet a safer place.