Checksum algorithms in JavaScript
Last Updated :
22 Nov, 2023
Checksum algorithms are fundamental techniques used in data communication and storage to ensure the integrity of data. The primary purpose of a checksum algorithm is to generate a fixed-size value (the checksum) based on the content of a dataset. They are essential for detecting errors, unauthorized changes, or corruption in data during transmission, saving files, or other data-handling processes.
These are the following techniques for this:
Simple Checksum
- It is a basic data integrity validation method. It generates a compact code to confirm if data is accurate, but it's simple and limited in detecting errors.
- In this approach, we will make a function
simpleChecksum
that calculates a checksum by summing the ASCII values of characters in the input data. - Now iterates through each character and accumulates their ASCII values into the checksum variable.
- Now to ensure the checksum stays within the 0-255 range, it uses modulo arithmetic.
Example: In this example, we will see the implementation of the checksum algorithm by using a simple checksum.
JavaScript
function simpleChecksum(data) {
let checksum = 0;
// Iterate through each character in the data
for (let i = 0; i < data.length; i++) {
// Add the ASCII value of
// the character to the checksum
checksum += data.charCodeAt(i);
}
// Ensure the checksum is within
//the range of 0-255 by using modulo
return checksum % 256;
}
const data = "GeeksForGeeks";
const checksumValue = simpleChecksum(data);
console.log("Simple Checksum: " + checksumValue);
CRC (Cyclic Redundancy Check)
- CRC (Cyclic Redundancy Check) is a more robust error-checking method. It computes a short, fixed-size value to confirm data accuracy. CRC is widely used in data communication and storage for error detection.
- The
calculateCRC
function computes a CRC-32 checksum using the polynomial 0xEDB88320. - Now iterates through each character, XORing it with the current CRC value, and performs bitwise operations.
- The algorithm ensures data integrity by incorporating bitwise XOR and a specific polynomial.
- Now final result, represented as a hexadecimal string, serves as a CRC-32 checksum for the given data
Example: In this example we will see the implementation of checksum algorithm by CRC method.
JavaScript
function calculateCRC(data) {
const polynomial = 0xEDB88320;
let crc = 0xFFFFFFFF;
// Iterate through each character in the data
for (let i = 0; i < data.length; i++) {
// XOR the current character
// with the current CRC value
crc ^= data.charCodeAt(i);
// Perform bitwise operations
// to calculate the new CRC value
for (let j = 0; j < 8; j++) {
crc = (crc >>> 1) ^ (crc & 1 ? polynomial : 0);
}
}
// Perform a final XOR operation and return the CRC value
return crc ^ 0xFFFFFFFF;
}
const data = "Geeks For Geeks";
const crcValue = calculateCRC(data);
console.log("CRC-32 Checksum: " +
crcValue.toString(16).toUpperCase());
OutputCRC-32 Checksum: -2C03EBB6
MD5 (Message Digest Algorithm 5)
- MD5 is a widely used cryptographic hash function. It generates a fixed-size, 32-character hash value from input data, providing data integrity and digital signature capabilities in various applications.
- In this approach, we will make a function
calculateMD5
that utilizes Node.js's crypto library to generate an MD5 checksum. - It creates an MD5 hash object, updates it with the provided data, and then produces the checksum.
- Now the resulting checksum, represented in hexadecimal, serves as a unique identifier for the input data.
Example: In this example we will see the implementation of checksum algorithm by using MD5.
JavaScript
const crypto = require("crypto");
// Calculate an MD5 checksum for the
// given data using Node.js's crypto library
function calculateMD5(data) {
// Create an MD5 hash object
const hash = crypto.createHash("md5");
// Update the hash object with the data
hash.update(data);
// Generate the MD5 checksum in hexadecimal format
return hash.digest("hex");
}
const data = "Geeks For Geeks";
const md5Value = calculateMD5(data);
console.log("MD5 Checksum: " + md5Value);
OutputMD5 Checksum: c5ea9d3ffad49b5874ca5a4da1d3c86e
SHA-256 (Secure Hash Algorithm 256-bit)
- SHA-256 is a robust cryptographic hash function. It computes a fixed-size, 64-character hash value from data, offering strong data integrity and security.
- Make a
calculateSHA256
function that employs Node.js's crypto library to compute a SHA-256 checksum. - It initializes a SHA-256 hash object, incorporates the provided data, and then produces the checksum.
- SHA-256 is a robust cryptographic hash function widely used for data integrity verification.
- Now the resulting checksum, presented in hexadecimal form, acts as a secure representation of the input data.
Example: In this example we will see the implementation of checksum algorithm by using SHA-256.
JavaScript
const crypto = require("crypto");
// Calculate a SHA-256 checksum for
// the given data using Node.js's crypto library
function calculateSHA256(data) {
// Create a SHA-256 hash object
const hash = crypto.createHash("sha256");
// Update the hash object with the data
hash.update(data);
// Generate the SHA-256 checksum
// in hexadecimal format
return hash.digest("hex");
}
const data = "HGeeks For Geeks";
const sha256Value = calculateSHA256(data);
console.log("SHA-256 Checksum: " + sha256Value);
OutputSHA-256 Checksum: c41f05cb05c78ab992132d4c4335774303e7a8e85600362bd6b5cdadf14229a5
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read