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:
-
HTML Structure:
- The HTML file includes a
<div>to display the output of the cryptographic hash calculation.
- The HTML file includes a
-
JavaScript (Web Crypto API):
calculateHashFunction:- Converts the text (
'Hello, Web Crypto API!') into anArrayBufferusingTextEncoder. - Uses
crypto.subtle.digest()to calculate the SHA-256 hash of theArrayBuffer. - Converts the resulting hash from an
ArrayBufferto a hexadecimal string for display. - Updates the content of the
<p id="output">element to show the original text and its SHA-256 hash.
- Converts the text (
How It Works:
- When the page loads (
window.onload), thecalculateHashfunction is called. - The text
'Hello, Web Crypto API!'is encoded into anArrayBuffer. - The SHA-256 hash of the
ArrayBufferis calculated usingcrypto.subtle.digest('SHA-256', encodedText). - The resulting hash is converted from an
ArrayBufferto a hexadecimal string and displayed on the web page.
Published on: Jun 18, 2024, 01:52 PM