How to build a hash generator application with React - LogRocket Blog (2024)

Introduction

Hash functions are often used to produce digital fingerprints of data.

Hashing is used most notably in the blockchain, which uses transaction information such as the amount being sent, transaction timestamps, and the sending and receiving address to generate a transaction ID. This information is combined and run through to a hash function to produce the ID, which is used to identify if the transaction has happened. Thus, this ID should be immutable, unique, secure, and free from collisions.

Hashing is also used to produce secure password algorithms. Storing plain text in any database can pose a major security threat. Whenever a user signs up using a plain text password, the password is run against a hash algorithm, and the hashed value is saved in a server.

When the user tries to log in using the password they used to sign up, the password is again passed through the same hash algorithm. The newly generated hash value is then compared against the previously saved hashed value on the server. If the newly calculated hash is the same as the one stored on the server, the password must be correct, and the user is granted login access.

This concept is based on the hash function terminology, which states same inputs will always provide the same outputs. This ensures no plain text passwords are stored in the database, thus ensuring no user data breaches between the user, application owner, or a hacker.

In this article, we will implement a hash generator application using React. React provides interactive user interface designs that allow you to create the necessary components that users can use to generate hashed values from texts and files. Our implementation will involve the SHA-1, SHA-256, SHA-384, and SHA-512 hashing algorithms.

What is hashing?

Hashing is the processing of converting a given random input value to generate completely unique keys. Hashing uses special mathematical functions called hashing algorithms, also known as hash functions, which are computations that converts an input value into a fixed-length, unique, and immutable hashed string. The input value can be a large number, a long string of text, or a combination of both. The function will always create a fixed-sized output, regardless of the length of the input value.

What makes a good hashing algorithm?

There are different hash algorithms that can be used to hash a given input. This includes SHA-1, SHA-256, SHA-384, and SHA-512 algorithms. A good hash algorithm needs to have certain qualities to be considered useful:

First, each hashed value has to be unique, which means different inputs should never produce the same value at any given time. This concept is called free collision, and states that it should be practically impossible to produce duplicate hashed value.

A hash should also have a fixed size. Using a given hash technique, you should always obtain fixed size hashes, regardless of how long the original input is. The size of the hashed value remains the same whether the data set is short or lengthy.

Next, a hash function should be fast to generate a hash value, and should always be random – any slightest change to the input value should always generate a completely different unique value.

Over 200k developers use LogRocket to create better digital experiencesLearn more →

Finally, hash algorithms should be secure; determining the input value based on the hash value should be nearly impossible.

Hashing differs from the concept of data encryption. The hashing process is always non-reversible, while encrypted data can be. Encryption is intended to function in two ways: you can encrypt data to keep it safe, and you can also decrypt the same data to reveal the original input.
This means that if attackers manage to steal the encryption key, they can unlock encrypted data. This is why encryption cannot generate values such as blockchain transaction IDs.

Prerequisites

To follow along with this guide, it is essential to have the following:

  • Working knowledge of hashing algorithms
  • Working knowledge of JavaScript and React
  • Node.js installed on your computer

Overview

  • Setting up a React application
  • Setting up the hashing component
  • Hashing text
  • Hashing file content
  • Handling algorithm switches
  • Conclusion

Setting up a React application

To set up our application, we will use Create React App, a command-line tool provided by React for conveniently bootstrapping your application. This creates a ready-to-use React application template.

To execute a Create React App template, navigate to your desired folder where you want your project to live. Then run the following command to initialize the application:

npx create-react-app hashing-app

Once the setup process is complete, you can test the template application by launching the development server. First, change your command line to point to the newly created application directory:

cd hashing-app

Then start the server using this npm command:

npm run start

Open http://localhost:3000 on your browser, and you should be able to access the default Create React App landing page.

How to build a hash generator application with React - LogRocket Blog (3)

Setting up the hashing component

In React, a component represents a part of the user interface. A component can be a page, header, footer, sidebar, or the main component that wraps other components. To create a hashing app with React, you need to set up a component that will let the user interact with different hashing functions.

To do this, navigate to your src folder, create a new directory, and name it components. Inside the components directory, create a hashing.js file for rendering the React component and hashing.css for styling the component.

Head over to the hashing.js create your component as shown in the following steps:

First, set up imports and a rendering function:

import React,{useState} from 'react';import './hashing.css';export default function HashingForm(){}

Here, we import the useState Hook. In React, you can have a state in your component that allows you to construct others. Then, we can use the state of that component to display information inside the render function.

From this step onwards, the rest of the code will go inside the rendering HashingForm() function.

Let’s begin by setting up our initial state:

const [algorithms] = useState(['sha1','sha256','sha384','sha512']);let [text_input, setTextInput] = useState('');let [file_input, setFileInput] = useState('');let [algorithm, setAlgorithm] = useState('sha1');let [output,setOutput] = useState('');

A state can be an array of values, Booleans, strings, objects, or any other data that a component uses. Here we have created some variables with useState. This will let us interact with values stored by these variables while generating different hash algorithms.

Next, set up the various onChange handlers:

// For handling text inputconst handleTextInput = async (e) => {}// For handling file inputconst handleFileInput = (e) => {}// For handling algorithm changeconst handleAlgorithmChange = async (e) => {}

The initial states we defined hold data that will change based on user interaction and the hash algorithm they want to generate. Thus, we have to set up the above handlers to track user reactions to events such as clicking a button.

More great articles from LogRocket:

  • Don't miss a moment with The Replay, a curated newsletter from LogRocket
  • Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
  • Use React's useEffect to optimize your application's performance
  • Switch between multiple versions of Node
  • Discover how to animate your React app with AnimXYZ
  • Explore Tauri, a new framework for building binaries
  • Compare NestJS vs. Express.js

Now we will render the input fields like so:

return ( <div className='hashing-container'> <div className='hashing-content'> // Start: Hashing form <div className="hashing-form"> <h4 className="hashing-form-heading">Input</h4> <form> <div className="form-group"> <label htmlFor="text-input">Text</label> <input type="text" className="form-control" id="text-input" placeholder='Write some text' value={text_input} onChange={handleTextInput} /> </div> <div className="form-group"> <label htmlFor="file-input">File Input</label> <input type="file" className="form-control" id="file-input" onChange={handleFileInput} /> </div> </form> </div> // End: Hashing form </div> </div>);

This template will set up a basic user input that allows users to enter different data they want to hash.

Next, render the hashing algorithms inside the hashing-content div, below the hashing-form div:

// Start: Hashing algorithms<div className="hashing-algorithms"> <h4 className="hashing-algorithms-heading">Algorithms</h4> <div className="hashing-algorithms-list"> { algorithms.map(algo => { return ( <div className="form-check" key={algo}> <input className="form-check-input" type="radio" name="algorithm" id={algo} value={algo} checked={algorithm === algo} onChange={handleAlgorithmChange} /> <label className="form-check-label" htmlFor={algo}> {algo} </label> </div> ) } )} </div></div>// End: Hashing algorithms

This template allows the user to select the hash algorithm they want to use.

Next, we will render the hashed output inside the hashing-container div, below the hashing-algorithms div:

// Start: Hashed output<div className="hashed-output"> <h4 className="hashed-algorithm-heading">Output</h4> <div className="hashed-algorithm-container"> <p className="hashed-algorithm-text"> {output} </p> </div></div>// End: Hashed output

While copying and pasting the above code templates, remember to remove the Start: and End: comments to ensure they are not rendered inside your component.

Once a user inputs the data to hash and selects the hash algorithm to use, we want to capture the hashed algorithm output and display it using the above template.

Next up is to style the component we have created. Add the following styles to the hashing.css file:

.hashing-container { width: 100%; height: 100vh; display: flex; justify-content: center; align-items: center;}.hashing-content { width: 40%; margin: 0px auto; padding: 10px; box-shadow: 0 1px 3px #d4d4d5, 0 0 0 1px #d4d4d5;}.form-group label { width: 100%; display: block; margin-bottom: 5px; font-weight: bold;}.form-group input[type="text"] { width: 94%; padding: 10px; border: 1px solid #d4d4d5; border-radius: 3px; margin-bottom: 5px;}.hashing-algorithms .hashing-algorithms-list { display: flex; justify-content: space-between;}.hashed-output .hashed-algorithm-container { width: 100%; border: 1px solid #d4d4d5;}.hashed-output .hashed-algorithm-text { padding: 10px; word-wrap: break-word; width: 90%;}

Head over to the src directory and edit App.js main component as follows:

import Hashing from './components/hashing'; // hashing componentfunction App() { return ( <div className="App"> <Hashing /> </div> );}export default App;

From above, we are importing and rendering the Hashing component as the main component of the page.

Let’s now test out if the created components work as expected. Ensure your development server is up and running and open http://localhost:3000 on your browser. If your server is not running, run npm run start before heading to http://localhost:3000.

Your landing page should now show the hashing component as below:

How to build a hash generator application with React - LogRocket Blog (4)

Hashing text

In this article, we will be using crypto-hash, a hashing package that uses the native crypto API.
To install it in your project, open a new terminal that points to your project folder and run the following command:

npm install crypto-hash

In src/components/hashing.js, add it to the list of imports:

import {sha1,sha256,sha384,sha512} from 'crypto-hash';

To hash a text, we will work on the handleTextInput onChange handler as follows:

const handleTextInput = async (e) => { // Get the value let value = e.target.value; let result = ''; // Get the current active algorithm and hash the value using it. if (algorithm == 'sha1') { result = await sha1(value); } else if (algorithm == 'sha256') { result = await sha256(value); } else if (algorithm == 'sha384') { result = await sha384(value); } else if (algorithm == 'sha512') { result = await sha512(value); } // Set the hashed text as output setOutput(result); // Set the value of the text input setTextInput(value);}

This will take in a text as the data value and hash it based on the user preference. A user can choose to use the SHA-1, SHA-256, SHA-384, or SHA-512 hashing algorithms. Once the text has been hashed, we will store the new value and update the setTextInput state. This new value will be displayed in the output section.

To test this out, head over to your React hashing page, input any text, and you should see the output section is rendered with the hashed text as follows:

How to build a hash generator application with React - LogRocket Blog (5)

Hashing file content

Similarly, to hash file content, we will work on the handleFileInput onChange handler as follows:

const handleFileInput = (e) => { // Initializing the file reader const fr = new FileReader(); // Listening to when the file has been read. fr.onload = async () => { let result = ''; // Hashing the content based on the active algorithm if (algorithm == 'sha1') { result = await sha1(fr.result); } else if (algorithm == 'sha256') { result = await sha256(fr.result); } else if (algorithm == 'sha384') { result = await sha384(fr.result); } else if (algorithm == 'sha512') { result = await sha512(fr.result); } // Setting the hashed text as the output setOutput(result); // Setting the content of the file as file input setFileInput(fr.result); } // Reading the file. fr.readAsText(e.target.files[0]);}

Choose any txt file from your computer, and you should be able to see the hashed content as follows:

How to build a hash generator application with React - LogRocket Blog (6)

Handling algorithm switches

Because we are working with different algorithms, we need to work on the handleAlgorithmChange onChange handler to visualize the hashed output from the various algorithms.

Edit the handler as follows:

const handleAlgorithmChange = async (e) => { // Get the selected algorithm let value = e.target.value; let result = ''; // Check if we have a text input if (text_input) { // Hash the text based on the selected algorithm if (value == 'sha1') { result = await sha1(text_input); } else if (value == 'sha256') { result = await sha256(text_input); } else if (value == 'sha384') { result = await sha384(text_input); } else if (value == 'sha512') { result = await sha512(text_input); } } // Check if we have a file input if (file_input) { // Hash the file content based on the selected algorithm if (value == 'sha1') { result = await sha1(file_input); } else if (value == 'sha256') { result = await sha256(file_input); } else if (value == 'sha384') { result = await sha384(file_input); } else if (value == 'sha512') { result = await sha512(file_input); } } // Set the selected algorithm setAlgorithm(value); // Set the hashed text setOutput(result);}

Now enter some text or choose a .txt file and switch between the algorithms, and you should see the hashed output change respectively.

Go ahead and try selecting different hashes and learn how different hashing algorithms convert your string of text and files to different values.

Conclusion

This article is a step-by-step guide to creating and implementing hash algorithms in a React application.

Hashes can be used in authentication apps such as logging systems, because a hash is always non-reversible. Once generated, the values can’t be changed. Each hash algorithm has a specific length of the hash output, and in this case, the length of the input text of the file doesn’t matter. The goal of the hash algorithm is to generate random and unique strings of hashes, thus, a slight change to the input value will always result in a completely different hashed value.

Check the code used in this article on this GitHub repository.

I hope you found this article helpful!

LogRocket: Full visibility into your production React apps

Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time,try LogRocket.

LogRocket combines session replay, product analytics, and error tracking – empowering software teams to create the ideal web and mobile product experience. What does that mean for you?

Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay problems as if they happened in your own browser to quickly understand what went wrong.

No more noisy alerting. Smart error tracking lets you triage and categorize issues, then learns from this. Get notified of impactful user issues, not false positives. Less alerts, way more useful signal.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps —start monitoring for free.

How to build a hash generator application with React - LogRocket Blog (2024)

FAQs

How do you create a hash in React? ›

To create a hashing app with React, you need to set up a component that will let the user interact with different hashing functions. To do this, navigate to your src folder, create a new directory, and name it components . Inside the components directory, create a hashing.

What is the strongest hash algorithm? ›

SHA-256 is one of the hashing algorithms that's part of the SHA-2 family (patented under a royalty-free U.S. patent 6829355). It's the most widely used and best hashing algorithm, often in conjunction with digital signatures, for: Authentication and encryption protocols, like TLS, SSL, SSH, and PGP.

Is Gatsby a toolchain for React application? ›

Gatsby is the best way to create static websites with React. It lets you use React components, but outputs pre-rendered HTML and CSS to guarantee the fastest load time. Learn Gatsby from its official guide and a gallery of starter kits.

What replaced create React app? ›

Alternative: React-Boilerplate

React-boilerplate is another tool that should be on the list for starting a React project. React-boilerplate portrays itself as the future of quick web apps on its home page and boasts that its software is accessible even when there is no network connection.

What hash is $1$? ›

$1$ is the prefix used to identify md5-crypt hashes, following the Modular Crypt Format. salt is 0-8 characters drawn from the regexp range [./0-9A-Za-z] ; providing a 48-bit salt ( 5pZSV9va in the example).

Which hash function is fastest? ›

xxHash is an Extremely fast Hash algorithm, running at RAM speed limits. It successfully completes the SMHasher test suite which evaluates collision, dispersion and randomness qualities of hash functions.

What is the weakest hashing algorithm? ›

The simplest hashing algorithm is parity, which with a single bit of output can't do miracles.

What is the safest hashing algorithm? ›

Common attacks like brute force attacks can take years or even decades to crack the hash digest, so SHA-2 is considered the most secure hash algorithm.

Is React used in metaverse? ›

One such type of app where developers can use React is eCommerce apps, which will be an essential part of the metaverse ecosystem.

Which CSS is best for React? ›

Grommet is the best CSS React framework with rich features and React UI libraries such as accessibility, modularity, responsiveness, and themes. The component package makes it simple to create responsive and accessible mobile-first websites.

Is React a MVC or MVVM? ›

React isn't an MVC framework.

React is a library for building composable user interfaces. It encourages the creation of reusable UI components which present data that changes over time.

Does Netflix still use React? ›

The React version works with Netflix too – specifically on their platform called Gibbon which is used for low-performance TV devices instead of the DOM used in web browsers.

Is React better than Python? ›

If you need a fast and responsive user interface, ReactJS is the better option. But if you need to handle complex data analysis or number-crunching, Python is the better language.

Is there anything better than React? ›

The open-source JavaScript framework is one of the most flexible, developer-friendly, and fastest alternatives available to developers right now. It has a flexible integration procedure and a smaller library size that allows Vue to offer enhanced performance while being easier to learn and adopt than React.

How long is a 128-bit hash? ›

MD5 yields hexadecimal digits (0-15 / 0-F), so they are four bits each. 128 / 4 = 32 characters.

What is a 128-bit hash? ›

MD5 (Message-Digest algorithm 5) is a widely used cryptographic hash function that results in a 128-bit hash value. The 128-bit (16-byte) MD5 hashes (also termed message digests) typically are represented as 32-digit hexadecimal numbers (for example, ec55d3e698d289f2afd663725127bace).

What hash is $5$? ›

$5$ is the prefix used to identify sha256-crypt hashes, following the Modular Crypt Format. rounds is the decimal number of rounds to use (80000 in the example). salt is 0-16 characters drawn from [./0-9A-Za-z] , providing a 96-bit salt ( wnsT7Yr92oJoP28r in the example).

What are the 3 types of hashing? ›

This article focuses on discussing different hash functions: Division Method. Mid Square Method. Folding Method.

Which two algorithms are used for hash? ›

There are multiple types of hashing algorithms, but the most common are Message Digest 5 (MD5) and Secure Hashing Algorithm (SHA) 1 and 2.

Can a hash be hacked? ›

If a system uses a properly designed algorithm to create a hashed password, chances of hacking are extremely low. However, when a hacker steals hashed passwords in a database, they can reverse engineer the hashes to get the real passwords by using a database of words they think might be the password.

Is hash faster than array? ›

Hash tables tend to be faster when it comes to searching for items. In arrays, you have to loop over all items before you find what you are looking for while in a hash table you go directly to the location of the item. Inserting an item is also faster in Hash tables since you just hash the key and insert it.

Is SHA-256 slow? ›

TL;DR; SHA1, SHA256, and SHA512 are all fast hashes and are bad for passwords. SCRYPT and BCRYPT are both a slow hash and are good for passwords.

What hash is 40 characters long? ›

SHA-1 is a hash function designed by the N.S.A. ("SHA" = "Secure Hash Algorithm"). It returns a 160-bit hexadecimal string which is 40 characters long. It was used for secure encryption from 1996 to 2010, largely as a replacement for MD5, but now it is used mostly for data integrity.

What are the 3 main types of cryptographic algorithms? ›

There are three general classes of NIST-approved cryptographic algorithms, which are defined by the number or types of cryptographic keys that are used with each.
  • Hash functions.
  • Symmetric-key algorithms.
  • Asymmetric-key algorithms.
  • Hash Functions.
  • Symmetric-Key Algorithms for Encryption and Decryption.
Oct 29, 2019

Is hashing a zero knowledge proof? ›

(2) in fact it's not truly zero-knowledge, formally it only satisfies a weaker definition known as honest-verifier zero-knowledge, but I omitted this point to simplify.

Are there any unbreakable encryption algorithms? ›

The Advanced Encryption Standard (AES) is a type of symmetric encryption that is considered both the most unbreakable algorithm and the global standard of security.

Is SHA-256 still secure? ›

Predictably, these are also the hashing algorithms that are often used when generating digital signatures and authenticating digital records. The problem is that, while they are all often used to verify data integrity, only SHA-256 is still secure—MD5 and SHA-1 have known vulnerabilities.

Which encryption algorithm is fastest? ›

Advanced Encryption Standard (AES) Algorithm

The Advanced Encryption Standard is the most common and extensively used symmetric encryption algorithm that is likely to be encountered nowadays (AES). It has been discovered to be at least six times quicker than triple DES.

Is SHA-256 algorithm secure? ›

SHA-256 is one of the most secure hashing functions on the market. The US government requires its agencies to protect certain sensitive information using SHA-256.

How to create hash code in JavaScript? ›

const hashCode = s => s. split(''). reduce((a,b) => (((a << 5) - a) + b. charCodeAt(0))|0, 0) // test console.

What is a hash link react? ›

React-router-hash-link allows you to leverage smooth scrolling seamlessly while using react-router-dom for routing. It has a lot of functions including Scroll to top and Scroll with offset functions, so you can explore what else it can do.

What does ${} do in react? ›

the ${} is the syntax for variables (or other code to be executed) inside template literals (`).

What does {} mean in react? ›

The curly braces are a special syntax to let the JSX parser know that it needs to interpret the contents in between them as JavaScript instead of a string. You need them when you want to use a JavaScript expression like a variable or a reference inside JSX.

Which algorithms can be used to generate a hash? ›

Some common hashing algorithms include MD5, SHA-1, SHA-2, NTLM, and LANMAN. MD5: This is the fifth version of the Message Digest algorithm. MD5 creates 128-bit outputs. MD5 was a very commonly used hashing algorithm.

Can hash be hacked? ›

However, when a hacker steals hashed passwords in a database, they can reverse engineer the hashes to get the real passwords by using a database of words they think might be the password. If any of the hashes match what the hacker has in the database, they now know the original password.

What are the 3 main properties of hash function? ›

In particular, cryptographic hash functions exhibit these three properties:
  • They are “collision-free.” This means that no two input hashes should map to the same output hash.
  • They can be hidden. It should be difficult to guess the input value for a hash function from its output.
  • They should be puzzle-friendly.

How does hash () work? ›

Hashing uses functions or algorithms to map object data to a representative integer value. A hash can then be used to narrow down searches when locating these items on that object data map. For example, in hash tables, developers store data -- perhaps a customer record -- in the form of key and value pairs.

What is the main purpose of hash? ›

Hash functions are used for data integrity and often in combination with digital signatures. With a good hash function, even a 1-bit change in a message will produce a different hash (on average, half of the bits change). With digital signatures, a message is hashed and then the hash itself is signed.

Top Articles
Latest Posts
Article information

Author: Greg O'Connell

Last Updated:

Views: 5946

Rating: 4.1 / 5 (62 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.