SHA-224 JavaScript SDK

Our JavaScript SDK provides a fast, efficient implementation of the SHA-224 cryptographic hash function for use in browsers, Node.js, and other JavaScript environments.

Universal Compatibility

Works seamlessly in browsers, Node.js, Deno, and serverless environments.

Web Crypto Integration

Uses the Web Crypto API when available for hardware-accelerated performance.

Pure JavaScript Fallback

Includes a pure JavaScript implementation for universal compatibility.

TypeScript Support

Includes type definitions for TypeScript projects.

Streaming API

Supports incremental hashing for large data streams.

REST API Integration

Seamlessly integrates with our REST API for server-side operations.

Installation

Install the SHA-224 JavaScript SDK using npm or yarn:

npm install @sha224/js
yarn add @sha224/js
<script src="https://cdn.sha224.com/js/sha224-1.2.3.min.js"></script>

You can also use unpkg:

<script src="https://unpkg.com/@sha224/[email protected]/dist/sha224.min.js"></script>

Quick Start

Generate SHA-224 hashes with just a few lines of code:

import { sha224 } from '@sha224/js';

// Hash a string
const hash = await sha224('Hello, world!');
console.log(hash); // '8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568'

// Hash binary data
const binaryData = new Uint8Array([1, 2, 3, 4, 5]);
const binaryHash = await sha224(binaryData);
console.log(binaryHash);
const { sha224 } = require('@sha224/js');

// Hash a string
sha224('Hello, world!')
  .then(hash => {
    console.log(hash); // '8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568'
  });

// Hash binary data
const binaryData = Buffer.from([1, 2, 3, 4, 5]);
sha224(binaryData)
  .then(binaryHash => {
    console.log(binaryHash);
  });
<!DOCTYPE html>
<html>
<head>
  <title>SHA-224 Example</title>
  <script src="https://cdn.sha224.com/js/sha224-1.2.3.min.js"></script>
</head>
<body>
  <script>
    // The library exposes a global sha224 object
    sha224.hash('Hello, world!')
      .then(hash => {
        console.log(hash); // '8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568'
      });
      
    // Hash a file from an input element
    document.getElementById('fileInput').addEventListener('change', async (event) => {
      const file = event.target.files[0];
      const fileHash = await sha224.hashFile(file);
      console.log(fileHash);
    });
  </script>
  
  <input type="file" id="fileInput">
</body>
</html>

API Reference

sha224(input, [options])

Computes a SHA-224 hash of the input data.

Parameters

  • input (string | ArrayBuffer | Uint8Array | Buffer | Blob | File) - The data to hash
  • options (object, optional) - Hash options
    • encoding (string, optional) - Input encoding for strings: 'utf8' (default), 'ascii', or 'hex'
    • outputFormat (string, optional) - Output format: 'hex' (default), 'bytes', or 'base64'
    • mode (string, optional) - Processing mode: 'auto' (default), 'webcrypto', 'js', or 'api'

Returns

Promise<string | Uint8Array> - The SHA-224 hash of the input

Example

// Basic usage
const hash = await sha224('Hello, world!');

// With options
const hash2 = await sha224('Hello, world!', {
  outputFormat: 'base64',
  mode: 'js' // Force pure JavaScript implementation
});

// Hash a file
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const fileHash = await sha224(file);

SHA224Hash (Class)

Class for incremental hashing of large data chunks.

Methods

  • constructor([options]) - Creates a new SHA224Hash instance
  • update(data) - Updates the hash with new data
  • digest([outputFormat]) - Finalizes the hash and returns the result
  • reset() - Resets the hash state

Example

import { SHA224Hash } from '@sha224/js';

// Create a hash instance
const hasher = new SHA224Hash();

// Update with chunks of data
hasher.update('Hello, ');
hasher.update('world!');

// Get the final hash
const hash = await hasher.digest();
console.log(hash); // '8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568'

// Reset and reuse
hasher.reset();
hasher.update('New data');
const newHash = await hasher.digest();

sha224.verify(hash, data, [options])

Verifies if the provided data matches the expected hash.

Parameters

  • hash (string) - The expected SHA-224 hash
  • data (string | ArrayBuffer | Uint8Array | Buffer | Blob | File) - The data to verify
  • options (object, optional) - Same options as the sha224() function

Returns

Promise<boolean> - True if the hash matches, false otherwise

Example

const expected = '8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568';
const isValid = await sha224.verify(expected, 'Hello, world!');
console.log(isValid); // true

sha224.hashFile(file, [options])

Convenience method for hashing a File or Blob object.

Parameters

  • file (File | Blob) - The file to hash
  • options (object, optional) - Hash options
    • outputFormat (string, optional) - Output format: 'hex' (default), 'bytes', or 'base64'
    • onProgress (function, optional) - Progress callback function
    • chunkSize (number, optional) - Size of chunks to read (default: 1MB)

Returns

Promise<string | Uint8Array> - The SHA-224 hash of the file

Example

// Hash a file with progress reporting
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];

const hash = await sha224.hashFile(file, {
  onProgress: (progress) => {
    console.log(`Hashing progress: ${Math.round(progress * 100)}%`);
    progressBar.value = progress;
  }
});

sha224.api

API client for interacting with the SHA224.com REST API.

Methods

  • configure(options) - Configure the API client
  • hashText(text, [options]) - Hash text using the API
  • hashFile(file, [options]) - Hash a file using the API
  • verify(hash, data, [options]) - Verify a hash using the API

Example

import { sha224 } from '@sha224/js';

// Configure the API client with your API key
sha224.api.configure({
  apiKey: 'YOUR_API_KEY',
  endpoint: 'https://api.sha224.com/v1'
});

// Hash text using the API
const hash = await sha224.api.hashText('Hello, world!');
console.log(hash);

// Verify a hash using the API
const isValid = await sha224.api.verify(hash, 'Hello, world!');
console.log(isValid);

Browser Usage

The SHA-224 JavaScript SDK is optimized for browser environments and provides several features specific to browser usage.

Web Crypto API Integration

In modern browsers, the SDK leverages the Web Crypto API for hardware-accelerated performance when available:

// By default, the SDK will use the Web Crypto API when available
const hash = await sha224('Hello, world!');

// Force Web Crypto API usage (will throw if not available)
const hash2 = await sha224('Hello, world!', { mode: 'webcrypto' });

// Check if Web Crypto is available
if (sha224.isWebCryptoSupported()) {
  console.log('Using hardware acceleration');
}

Hashing Files in the Browser

The SDK provides specialized methods for working with files in the browser:

// Drag and drop file hashing
const dropZone = document.getElementById('dropZone');

dropZone.addEventListener('drop', async (event) => {
  event.preventDefault();
  
  const file = event.dataTransfer.files[0];
  const progressBar = document.getElementById('progressBar');
  
  const hash = await sha224.hashFile(file, {
    onProgress: (progress) => {
      progressBar.value = progress;
      document.getElementById('percentage').textContent = 
        `${Math.round(progress * 100)}%`;
    }
  });
  
  document.getElementById('hashResult').textContent = hash;
});

dropZone.addEventListener('dragover', (event) => {
  event.preventDefault();
});

Workers Integration

For improved performance with large files, the SDK can operate in a Web Worker:

// In your main application
import { createWorker } from '@sha224/js/worker';

const worker = createWorker();

// Hash files without blocking the UI
document.getElementById('fileInput').addEventListener('change', (event) => {
  const file = event.target.files[0];
  
  worker.hashFile(file, {
    onProgress: (progress) => {
      progressBar.value = progress;
    }
  }).then(hash => {
    console.log('File hash:', hash);
  });
});

Browser Support

The SHA-224 JavaScript SDK supports all modern browsers:

  • Chrome 49+
  • Firefox 42+
  • Safari 10.1+
  • Edge 14+
  • Opera 36+
  • iOS Safari 10.3+
  • Android Browser 67+

For older browsers, the SDK uses a pure JavaScript implementation to ensure compatibility.

Node.js Usage

The SHA-224 JavaScript SDK is fully compatible with Node.js environments and provides additional features for server-side usage.

Node.js Crypto Integration

In Node.js, the SDK integrates with the native crypto module:

const { sha224, SHA224Hash } = require('@sha224/js');

// Hash a string
sha224('Hello, world!').then(hash => {
  console.log(hash);
});

// Hash a file using streams
const fs = require('fs');
const hasher = new SHA224Hash();

fs.createReadStream('large-file.bin')
  .on('data', chunk => hasher.update(chunk))
  .on('end', () => {
    hasher.digest().then(hash => {
      console.log('File hash:', hash);
    });
  });

Working with Buffers

The SDK has optimized handling for Node.js Buffer objects:

const { sha224 } = require('@sha224/js');
const fs = require('fs');

// Hash from a buffer
const buffer = Buffer.from('Hello, world!');
sha224(buffer).then(hash => {
  console.log(hash);
});

// Read a file synchronously and hash it
const fileBuffer = fs.readFileSync('file.txt');
sha224(fileBuffer).then(hash => {
  console.log('File hash:', hash);
});

API Integration

The SDK provides an HTTP client for interacting with the SHA224.com API from Node.js:

const { sha224 } = require('@sha224/js');

// Configure the API client
sha224.api.configure({
  apiKey: process.env.SHA224_API_KEY
});

// Use the API client
async function verifyFileWithAPI(filePath, expectedHash) {
  const fs = require('fs');
  const fileBuffer = fs.readFileSync(filePath);
  
  const isValid = await sha224.api.verify(expectedHash, fileBuffer);
  return isValid;
}

Command Line Interface

When installed globally, the SDK provides a command-line interface for hashing files:

# Install globally
npm install -g @sha224/js

# Hash a file from the command line
sha224 file.txt

# With specific options
sha224 file.txt --output=base64 --mode=js

TypeScript Support

The SHA-224 JavaScript SDK includes comprehensive TypeScript definitions.

import { sha224, SHA224Hash, SHA224Options, OutputFormat } from '@sha224/js';

// Type-safe options
const options: SHA224Options = {
  encoding: 'utf8',
  outputFormat: 'hex' as OutputFormat,
  mode: 'auto'
};

// Async usage with proper typing
async function hashData(data: string | Uint8Array): Promise<string> {
  const hash = await sha224(data, options);
  return hash;
}

// Incremental hashing with types
const hasher = new SHA224Hash();
hasher.update('Hello');
hasher.update(new Uint8Array([1, 2, 3]));
const result = await hasher.digest();

The SDK exports the following types:

  • SHA224Options - Options for hash operations
  • InputEncoding - Input encoding types
  • OutputFormat - Output format types
  • ProcessingMode - Hash processing mode types
  • ProgressCallback - Callback function for hashing progress
  • APIOptions - Options for API client configuration

Examples

Basic Usage Examples

Hashing Strings

import { sha224 } from '@sha224/js';

// Hash a simple string
const hash1 = await sha224('Hello, world!');

// Hash with different encodings
const hash2 = await sha224('48656c6c6f2c20776f726c6421', { encoding: 'hex' });

// Different output formats
const hexHash = await sha224('test', { outputFormat: 'hex' });
const base64Hash = await sha224('test', { outputFormat: 'base64' });
const bytesHash = await sha224('test', { outputFormat: 'bytes' }); // Returns Uint8Array

Hashing Binary Data

// Hash an array buffer
const buffer = new ArrayBuffer(4);
const view = new Uint32Array(buffer);
view[0] = 0x12345678;
const bufferHash = await sha224(buffer);

// Hash a typed array
const uint8Array = new Uint8Array([72, 101, 108, 108, 111]); // "Hello" in ASCII
const uint8Hash = await sha224(uint8Array);

File Hashing Examples

Browser File Hashing

// Hash a file selected via input element
document.getElementById('fileInput').addEventListener('change', async (event) => {
  const file = event.target.files[0];
  const progressBar = document.getElementById('progressBar');
  const resultDiv = document.getElementById('result');
  
  try {
    resultDiv.textContent = 'Hashing...';
    
    const hash = await sha224.hashFile(file, {
      onProgress: (progress) => {
        progressBar.style.width = `${Math.round(progress * 100)}%`;
        progressBar.textContent = `${Math.round(progress * 100)}%`;
      }
    });
    
    resultDiv.textContent = `SHA-224 hash: ${hash}`;
  } catch (error) {
    resultDiv.textContent = `Error: ${error.message}`;
  }
});

Node.js File Hashing

const { sha224, SHA224Hash } = require('@sha224/js');
const fs = require('fs');

// Method 1: Read file and hash
fs.readFile('large-file.bin', (err, data) => {
  if (err) throw err;
  
  sha224(data).then(hash => {
    console.log(`SHA-224 hash: ${hash}`);
  });
});

// Method 2: Streaming for large files
const hasher = new SHA224Hash();
let totalSize = 0;
const fileSize = fs.statSync('large-file.bin').size;

const stream = fs.createReadStream('large-file.bin');
stream.on('data', (chunk) => {
  hasher.update(chunk);
  totalSize += chunk.length;
  const progress = totalSize / fileSize;
  console.log(`Progress: ${Math.round(progress * 100)}%`);
});

stream.on('end', () => {
  hasher.digest().then(hash => {
    console.log(`SHA-224 hash: ${hash}`);
  });
});

API Integration Examples

Basic API Usage

import { sha224 } from '@sha224/js';

// Configure API client
sha224.api.configure({
  apiKey: 'YOUR_API_KEY',
  endpoint: 'https://api.sha224.com/v1'
});

// Hash text using the API
const apiHash = await sha224.api.hashText('Hello, world!');
console.log(`API hash: ${apiHash}`);

// Verify a hash using the API
const isValid = await sha224.api.verify(
  '8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568',
  'Hello, world!'
);
console.log(`Hash verification: ${isValid ? 'Valid' : 'Invalid'}`);

Advanced API Usage

import { sha224 } from '@sha224/js';

// Configure with additional options
sha224.api.configure({
  apiKey: 'YOUR_API_KEY',
  endpoint: 'https://api.sha224.com/v1',
  timeout: 10000, // 10 seconds
  retryAttempts: 3
});

// Batch hash multiple items
const batchResults = await sha224.api.batchHash([
  { id: 'item1', text: 'First item' },
  { id: 'item2', text: 'Second item' },
  { id: 'item3', text: 'Third item' }
]);

console.log(batchResults);

// Batch verify multiple hashes
const verifyResults = await sha224.api.batchVerify([
  { 
    id: 'item1', 
    hash: '7d92e8759c21ff6243e249061231d33fbf16cd78b38d8245741bd128',
    text: 'First item'
  },
  { 
    id: 'item2',
    hash: 'a7788f21fa20193c29b0e1156f0ff72f68da050befd5057b9946b652',
    text: 'Second item'
  }
]);

console.log(verifyResults);

Advanced Examples

Custom Implementation Selection

import { sha224 } from '@sha224/js';

// Automatic selection (default)
const autoHash = await sha224('data', { mode: 'auto' });

// Force Web Crypto API
try {
  const webCryptoHash = await sha224('data', { mode: 'webcrypto' });
  console.log('Using Web Crypto API:', webCryptoHash);
} catch (error) {
  console.error('Web Crypto not available:', error);
}

// Force pure JavaScript implementation
const jsHash = await sha224('data', { mode: 'js' });
console.log('Using pure JS implementation:', jsHash);

// Force API implementation
const apiHash = await sha224('data', { mode: 'api' });
console.log('Using API implementation:', apiHash);

Incremental Hashing for Large Data

import { SHA224Hash } from '@sha224/js';

// Create a new hash instance
const hasher = new SHA224Hash();

// Simulate processing a large file in chunks
function processLargeData() {
  let processedBytes = 0;
  const totalSize = 1024 * 1024 * 100; // 100 MB
  const chunkSize = 1024 * 1024; // 1 MB
  
  return new Promise((resolve) => {
    function processNextChunk() {
      // Generate a chunk of random data
      const chunk = new Uint8Array(Math.min(chunkSize, totalSize - processedBytes));
      crypto.getRandomValues(chunk);
      
      // Update the hash with this chunk
      hasher.update(chunk);
      
      processedBytes += chunk.length;
      const progress = processedBytes / totalSize;
      console.log(`Progress: ${Math.round(progress * 100)}%`);
      
      if (processedBytes < totalSize) {
        // Process next chunk
        setTimeout(processNextChunk, 0);
      } else {
        // Finalize the hash
        hasher.digest().then(resolve);
      }
    }
    
    processNextChunk();
  });
}

processLargeData().then(hash => {
  console.log(`Final hash: ${hash}`);
});

Content-Addressable Storage

// Simple content-addressable storage using SHA-224
class ContentStore {
  constructor() {
    this.store = new Map();
  }
  
  async put(content) {
    const hash = await sha224(content);
    this.store.set(hash, content);
    return hash;
  }
  
  get(hash) {
    return this.store.get(hash);
  }
  
  async verify(hash, content) {
    const computedHash = await sha224(content);
    return computedHash === hash;
  }
}

// Usage
const store = new ContentStore();
const content = 'This is some content to store';
const hash = await store.put(content);

console.log(`Content stored with hash: ${hash}`);
console.log(`Retrieved content: ${store.get(hash)}`);

Frequently Asked Questions

What's the difference between SHA-224 and SHA-256?

SHA-224 is a truncated version of SHA-256 that produces a 224-bit (28-byte) hash value instead of 256 bits. It uses a different initial value than SHA-256 and truncates the final hash to 224 bits. This provides a good balance between security and output size, making it suitable for applications where space is a concern but strong security is still required.

For more details, see our SHA-224 vs SHA-256 comparison.

Which implementation mode should I use?

The SDK supports different implementation modes:

  • auto (default): Automatically selects the best available implementation
  • webcrypto: Uses the Web Crypto API (fastest in browsers with hardware support)
  • js: Uses the pure JavaScript implementation (works everywhere)
  • api: Uses the SHA224.com REST API (requires an API key and internet connection)

For most applications, using the default 'auto' mode is recommended as it will select the optimal implementation based on the environment.

Is the SDK secure for cryptographic purposes?

Yes, the SHA-224 JavaScript SDK implements the SHA-224 algorithm according to the FIPS 180-4 standard. When using the Web Crypto API or Node.js crypto modules, it leverages native implementations that are hardened against timing attacks.

The pure JavaScript implementation is also designed to be constant-time to mitigate timing attacks, but for the highest security applications, we recommend using the Web Crypto API or Node.js crypto implementation where available.

How does the SDK handle large files?

The SDK efficiently handles large files through:

  • Chunked processing: Files are processed in smaller chunks to avoid memory issues
  • Stream support: In Node.js, files can be streamed directly through the hasher
  • Progressive reading: In browsers, the FileReader API is used to read files progressively
  • Web Workers: Optional Web Worker support to avoid blocking the UI thread
  • Progress reporting: Callbacks for monitoring hashing progress

For very large files (multi-gigabyte), consider using the incremental hashing API with the SHA224Hash class or the API-based implementation which can handle server-side processing.

Do I need an API key to use the SDK?

No, the SDK can be used without an API key for local hashing operations. The SDK includes both client-side implementations (Web Crypto API and pure JavaScript) that work without any server interaction.

You only need an API key if you want to use the SHA224.com REST API for server-side processing or additional features like batch operations. An API key can be obtained by signing up at app.sha224.com.

Next Steps

API Documentation

Learn about the complete REST API.

View API Docs

Implementation Guide

Step-by-step implementation guide.

View Guide

Examples Repository

Explore more code examples.

View Examples