Try it yourself with our free Hash Generator tool — runs entirely in your browser, no signup needed.

How to Generate SHA-256 hash in TypeScript

How to generate SHA-256 hash in TypeScript

In today's digital age, data integrity and security are of utmost importance. One way to ensure data integrity is by generating a digital fingerprint, known as a hash, using algorithms like SHA-256. In this article, we will explore how to generate a SHA-256 hash in TypeScript, a popular language for building scalable and maintainable applications.

Quick Example

Here is a minimal example to get you started:

import * as crypto from 'crypto';

const input = 'Hello, World!';
const hash = crypto.createHash('sha256').update(input).digest('hex');
console.log(hash);

This code generates a SHA-256 hash for the input string 'Hello, World!' and logs the result to the console.

Step-by-Step Breakdown

Let's walk through the code line by line:

  • import * as crypto from 'crypto';: We import the crypto module, which provides cryptographic functions, including hash generation.
  • const input = 'Hello, World!';: We define the input string for which we want to generate the hash.
  • const hash = crypto.createHash('sha256').update(input).digest('hex');: This line is where the magic happens.
    • crypto.createHash('sha256'): We create a new SHA-256 hash object using the createHash() method.
    • .update(input): We update the hash object with the input string using the update() method.
    • .digest('hex'): We generate the hash digest in hexadecimal format using the digest() method.
  • console.log(hash);: Finally, we log the generated hash to the console.

Handling Edge Cases

Here are some common edge cases to consider:

Empty/null input

If the input is empty or null, the hash will be generated for an empty string.

const input = '';
const hash = crypto.createHash('sha256').update(input).digest('hex');
console.log(hash); // Output: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

Invalid input

If the input is not a string, you may want to handle the error or convert it to a string before generating the hash.

const input = 123;
try {
  const hash = crypto.createHash('sha256').update(input).digest('hex');
  console.log(hash);
} catch (error) {
  console.error('Invalid input:', error);
}

Large input

For large inputs, you can use the update() method multiple times to feed the input in chunks.

const input = 'This is a very large input...';
const chunkSize = 1024;
const hash = crypto.createHash('sha256');
for (let i = 0; i < input.length; i += chunkSize) {
  hash.update(input.slice(i, i + chunkSize));
}
console.log(hash.digest('hex'));

Unicode/special characters

SHA-256 handles Unicode and special characters without issues.

const input = 'Hello, Sérgio!';
const hash = crypto.createHash('sha256').update(input).digest('hex');
console.log(hash);

Common Mistakes

Here are some common mistakes to avoid:

1. Using the wrong algorithm

Make sure to use the correct algorithm, in this case, 'sha256'.

// Wrong
const hash = crypto.createHash('md5').update(input).digest('hex');
// Correct
const hash = crypto.createHash('sha256').update(input).digest('hex');

2. Not handling errors

Always handle errors when working with cryptographic functions.

// Wrong
const hash = crypto.createHash('sha256').update(input).digest('hex');
// Correct
try {
  const hash = crypto.createHash('sha256').update(input).digest('hex');
} catch (error) {
  console.error('Error:', error);
}

3. Not using hexadecimal format

Make sure to use the hexadecimal format when generating the hash digest.

// Wrong
const hash = crypto.createHash('sha256').update(input).digest();
// Correct
const hash = crypto.createHash('sha256').update(input).digest('hex');

Performance Tips

Here are some performance tips to keep in mind:

1. Use the update() method for large inputs

For large inputs, use the update() method multiple times to feed the input in chunks.

2. Avoid unnecessary conversions

Avoid converting the input to a string or buffer unnecessarily, as this can impact performance.

3. Use the crypto module

Use the built-in crypto module, as it is optimized for performance and security.

FAQ

Q: What is the output format of the hash digest?

A: The output format of the hash digest is hexadecimal.

Q: Can I use SHA-256 for password storage?

A: No, SHA-256 is not suitable for password storage. Use a password hashing algorithm like bcrypt instead.

Q: Is SHA-256 secure?

A: SHA-256 is considered secure for most use cases. However, for very high-security applications, consider using a more secure algorithm like SHA-3.

Q: Can I use SHA-256 for data encryption?

A: No, SHA-256 is a one-way hash function and cannot be used for data encryption. Use a encryption algorithm like AES instead.

Q: How do I install the crypto module?

A: The crypto module is built-in to Node.js, so no installation is required.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp