Home  Nodejs   The web cry ...

The Web Crypto API example

The Web Crypto API (crypto.subtle) provides cryptographic functionalities directly in web browsers, allowing developers to perform secure operations such as hashing, encryption, decryption, digital signatures, and key generation. Here's a simple example demonstrating the usage of the Web Crypto API to generate a cryptographic hash (SHA-256) of a string:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Web Crypto API Example</title>
</head>
<body>
  <div>
    <h2>Web Crypto API Example</h2>
    <p id="output"></p>
  </div>

  <script>
    async function calculateHash() {
      const text = 'Hello, Web Crypto API!';
      
      // Convert text to ArrayBuffer
      const encodedText = new TextEncoder().encode(text);
      
      // Calculate SHA-256 hash
      const hashBuffer = await crypto.subtle.digest('SHA-256', encodedText);
      
      // Convert hash ArrayBuffer to hexadecimal string
      const hashArray = Array.from(new Uint8Array(hashBuffer));
      const hashHex = hashArray.map(byte => ('00' + byte.toString(16)).slice(-2)).join('');
      
      // Display hash result
      const outputElement = document.getElementById('output');
      outputElement.textContent = `Text: ${text}\nSHA-256 Hash: ${hashHex}`;
    }

    // Call calculateHash function when the page loads
    window.onload = calculateHash;
  </script>
</body>
</html>

Explanation:

  1. HTML Structure:

    • The HTML file includes a <div> to display the output of the cryptographic hash calculation.
  2. JavaScript (Web Crypto API):

    • calculateHash Function:
      • Converts the text ('Hello, Web Crypto API!') into an ArrayBuffer using TextEncoder.
      • Uses crypto.subtle.digest() to calculate the SHA-256 hash of the ArrayBuffer.
      • Converts the resulting hash from an ArrayBuffer to a hexadecimal string for display.
      • Updates the content of the <p id="output"> element to show the original text and its SHA-256 hash.

How It Works:

Published on: Jun 18, 2024, 01:52 PM  
 

Comments

Add your comment