SHA-224 API Reference

Comprehensive reference documentation for the SHA-224 cryptographic hash function

API Overview

The SHA224.com API provides multiple ways to calculate and verify SHA-224 hashes, allowing you to choose the approach that best fits your application's needs. This reference document covers both client-side APIs for direct integration into your applications and our hosted REST API for server-to-server communication.

API Type Description Best For
Client-Side JavaScript Direct implementation that runs in browser or Node.js Client-side validation, offline applications
REST API HTTP-based API for server-to-server communication Server-side processing, cross-platform integration
Client SDKs Language-specific libraries that interface with the REST API Simplified integration in supported languages

Client-Side API

The SHA224.com client-side JavaScript API provides a complete implementation of the SHA-224 hash function that can run directly in your browser or Node.js application. The API offers both functional and object-oriented approaches to suit different coding styles.

Installation

<!-- Add to your HTML head -->
<script src="https://cdn.sha224.com/js/sha224.min.js"></script>
# Install from NPM
npm install @sha224/hash

# Import in your code
const SHA224 = require('@sha224/hash');
// Or using ES modules
import SHA224 from '@sha224/hash';
<!-- Download the script -->
<a href="https://sha224.com/js/sha224.js" download>Download sha224.js</a>

<!-- Include in your project -->
<script src="path/to/sha224.js"></script>

Function-Based API

The function-based API provides a simple way to calculate SHA-224 hashes with minimal code. This approach is ideal for one-off hash calculations where you don't need to maintain state between operations.

SHA224(message)

Calculates the SHA-224 hash of the provided message.

Parameters
Parameter Type Description
message String | Uint8Array The message to hash. If a string is provided, it will be converted to UTF-8 bytes. For binary data, provide a Uint8Array.
Returns

String - The SHA-224 hash as a lowercase hexadecimal string (56 characters)

Examples
// Hash a string
const hash = SHA224('Hello, world!');
console.log(hash);
// Output: 8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568

// Hash binary data
const binaryData = new Uint8Array([72, 101, 108, 108, 111]); // "Hello" in ASCII
const binaryHash = SHA224(binaryData);
console.log(binaryHash);
// Output: ea09ae9cc6768c50fcee903ed054556e5bfc8347907f12598aa24193

SHA224.hash(message)

An alias for the SHA224(message) function. Behaves exactly the same way.

Example
const hash = SHA224.hash('Hello, world!');
// Output: 8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568

Class-Based API

The class-based API provides an object-oriented approach that allows for incremental (chunked) hashing. This is useful when processing large data or when data is available in chunks (such as during file uploads).

SHA224Class

The SHA224Class represents a SHA-224 hash computation context.

Constructor
// Create a new hash context
const hasher = new SHA224Class();
Methods
.update(message)

Updates the hash computation with the specified message. Can be called multiple times to process data in chunks.

Parameters
Parameter Type Description
message String | Uint8Array The message chunk to add to the hash computation. If a string is provided, it will be converted to UTF-8 bytes. For binary data, provide a Uint8Array.
Returns

SHA224Class - The hash context (for method chaining)

Example
const hasher = new SHA224Class();
hasher.update('Hello');
hasher.update(', ');
hasher.update('world!');
// Continue with more data...
.digest()

Finalizes the hash computation and returns the resulting hash value.

Returns

String - The SHA-224 hash as a lowercase hexadecimal string (56 characters)

Example
const hasher = new SHA224Class();
hasher.update('Hello, ');
hasher.update('world!');
const hash = hasher.digest();
console.log(hash);
// Output: 8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568
Static Methods
SHA224Class.hash(message)

A convenience method that creates a new SHA224Class instance, updates it with the provided message, and returns the digest.

Parameters
Parameter Type Description
message String | Uint8Array The message to hash. If a string is provided, it will be converted to UTF-8 bytes. For binary data, provide a Uint8Array.
Returns

String - The SHA-224 hash as a lowercase hexadecimal string

Example
const hash = SHA224Class.hash('Hello, world!');
console.log(hash);
// Output: 8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568

Hash Verification

The API provides methods for verifying that a message matches an expected hash value.

SHA224.verify(message, expectedHash)

Verifies that the SHA-224 hash of the provided message matches the expected hash value.

Parameters
Parameter Type Description
message String | Uint8Array The message to verify. If a string is provided, it will be converted to UTF-8 bytes. For binary data, provide a Uint8Array.
expectedHash String The expected SHA-224 hash as a hexadecimal string. Case-insensitive.
Returns

Boolean - true if the calculated hash matches the expected hash, false otherwise

Example
// Verify a message matches an expected hash
const isValid = SHA224.verify(
  'Hello, world!', 
  '8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568'
);
console.log('Hash verification result:', isValid ? 'Valid' : 'Invalid');
// Output: Hash verification result: Valid

// Case-insensitive comparison
const isValidUppercase = SHA224.verify(
  'Hello, world!', 
  '8552D8B7A7DC5476CB9E25DEE69A8091290764B7F2A64FE6E78E9568'
);
console.log('Case-insensitive verification:', isValidUppercase ? 'Valid' : 'Invalid');
// Output: Case-insensitive verification: Valid

REST API

The SHA224.com REST API provides a serverless approach to hash generation and verification through simple HTTP requests. This is ideal for server-side applications or environments where implementing the hash algorithm directly is not practical.

Base URL

https://api.sha224.com/v1

Authentication

All API requests require authentication using your API key, which can be included in one of two ways:

Authorization Header (Recommended)

Authorization: Bearer YOUR_API_KEY

Query Parameter

https://api.sha224.com/v1/hash?api_key=YOUR_API_KEY

Hash Generation

POST
/hash

Calculates the SHA-224 hash of the provided data.

Request Parameters

Parameter Type Required Description
data String Yes The data to hash
encoding String No The encoding of the input data. Valid values:
  • utf8 (default): UTF-8 encoded text
  • hex: Hexadecimal string
  • base64: Base64 encoded data
outputFormat String No The output format of the hash. Valid values:
  • hex (default): Hexadecimal string
  • base64: Base64 encoded hash
  • binary: Raw binary data (returned as base64)

Response

{
  "success": true,
  "hash": "8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568",
  "algorithm": "sha224",
  "encoding": "hex",
  "timestamp": "2025-05-15T10:30:15Z"
}

Example Request

curl -X POST \
  https://api.sha224.com/v1/hash \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "data": "Hello, world!",
    "encoding": "utf8"
  }'

Hash Verification

POST
/verify

Verifies that the SHA-224 hash of the provided data matches the expected hash value.

Request Parameters

Parameter Type Required Description
data String Yes The data to verify
hash String Yes The expected SHA-224 hash (hexadecimal)
encoding String No The encoding of the input data. Valid values:
  • utf8 (default): UTF-8 encoded text
  • hex: Hexadecimal string
  • base64: Base64 encoded data

Response

{
  "success": true,
  "verified": true,
  "algorithm": "sha224",
  "timestamp": "2025-05-15T10:31:45Z"
}

Example Request

curl -X POST \
  https://api.sha224.com/v1/verify \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "data": "Hello, world!",
    "hash": "8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568",
    "encoding": "utf8"
  }'

File Hashing

POST
/file/hash

Calculates the SHA-224 hash of an uploaded file.

Request Parameters

This endpoint accepts multipart/form-data with the following fields:

Parameter Type Required Description
file File Yes The file to hash (maximum size: 25MB for standard accounts)
outputFormat String No The output format of the hash. Valid values:
  • hex (default): Hexadecimal string
  • base64: Base64 encoded hash

Response

{
  "success": true,
  "hash": "7c5ef6ce3ae40c0d2a917a4dc21742086c01f72d6c72cb85e6941189",
  "algorithm": "sha224",
  "encoding": "hex",
  "fileName": "document.pdf",
  "fileSize": 1052672,
  "timestamp": "2025-05-15T10:33:22Z"
}

Example Request

curl -X POST \
  https://api.sha224.com/v1/file/hash \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -F 'file=@/path/to/document.pdf'

HMAC Generation

POST
/hmac

Generates an HMAC (Hash-based Message Authentication Code) using SHA-224 and the provided key.

Request Parameters

Parameter Type Required Description
data String Yes The data to authenticate
key String Yes The secret key for HMAC generation
encoding String No The encoding of the input data. Valid values:
  • utf8 (default): UTF-8 encoded text
  • hex: Hexadecimal string
  • base64: Base64 encoded data
keyEncoding String No The encoding of the key. Valid values:
  • utf8 (default): UTF-8 encoded text
  • hex: Hexadecimal string
  • base64: Base64 encoded data
outputFormat String No The output format of the HMAC. Valid values:
  • hex (default): Hexadecimal string
  • base64: Base64 encoded HMAC

Response

{
  "success": true,
  "hmac": "c5ab54a9a547c7dea70e756f78d0a4f97d6a506ef25e0666dba872a0",
  "algorithm": "sha224",
  "encoding": "hex",
  "timestamp": "2025-05-15T10:35:12Z"
}

Example Request

curl -X POST \
  https://api.sha224.com/v1/hmac \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "data": "Message to authenticate",
    "key": "secretKey123",
    "encoding": "utf8",
    "keyEncoding": "utf8"
  }'

Usage Statistics

GET
/usage

Retrieves information about your API usage and remaining quota.

Request Parameters

This endpoint does not require any parameters.

Response

{
  "success": true,
  "account": {
    "tier": "developer",
    "quota": {
      "daily": 50000,
      "used": 1547,
      "remaining": 48453,
      "resetTime": "2025-05-16T00:00:00Z"
    },
    "rateLimit": {
      "requestsPerSecond": 20,
      "maxFileSize": 25000000
    }
  },
  "timestamp": "2025-05-15T10:36:30Z"
}

Example Request

curl -X GET \
  https://api.sha224.com/v1/usage \
  -H 'Authorization: Bearer YOUR_API_KEY'

Client SDKs

To simplify integration with our REST API, we provide official client SDKs for popular programming languages. These SDKs handle API authentication, request formatting, and error handling for you.

JavaScript Icon

JavaScript/TypeScript

npm install @sha224/sdk
Python Icon

Python

pip install sha224-sdk
Java Icon

Java

com.sha224:sha224-sdk:1.0.0
Go Icon

Go

go get github.com/sha224/go-sdk
Ruby Icon

Ruby

gem install sha224-sdk
PHP Icon

PHP

composer require sha224/sdk

Example Implementations

Below are examples of common SHA-224 implementation patterns across different use cases.

// Basic text hashing example

// Client-side JavaScript
function hashTextExample() {
  const textInput = 'Hello, world!';
  
  // Using function-based API
  const hash1 = SHA224(textInput);
  console.log('Function API result:', hash1);
  
  // Using class-based API
  const hasher = new SHA224Class();
  hasher.update(textInput);
  const hash2 = hasher.digest();
  console.log('Class API result:', hash2);
  
  // Verification
  const isValid = SHA224.verify(textInput, hash1);
  console.log('Verification result:', isValid ? 'Valid' : 'Invalid');
}

// Node.js with REST API
async function hashTextWithAPI() {
  const apiKey = 'YOUR_API_KEY';
  const textInput = 'Hello, world!';
  
  try {
    const response = await fetch('https://api.sha224.com/v1/hash', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        data: textInput,
        encoding: 'utf8'
      })
    });
    
    const result = await response.json();
    console.log('API hash result:', result.hash);
  } catch (error) {
    console.error('API error:', error);
  }
}
// File hashing example

// Browser-side file hashing
async function hashFileInBrowser() {
  const fileInput = document.getElementById('fileInput');
  const file = fileInput.files[0];
  
  if (!file) {
    console.error('No file selected');
    return;
  }
  
  try {
    // Read file as ArrayBuffer
    const arrayBuffer = await file.arrayBuffer();
    const fileData = new Uint8Array(arrayBuffer);
    
    // Generate hash
    const hash = SHA224(fileData);
    console.log(`File hash (${file.name}):`, hash);
    
    return hash;
  } catch (error) {
    console.error('Error hashing file:', error);
  }
}

// Node.js file hashing with REST API
async function hashFileWithAPI(filePath) {
  const apiKey = 'YOUR_API_KEY';
  const fs = require('fs');
  const FormData = require('form-data');
  const fetch = require('node-fetch');
  
  try {
    const form = new FormData();
    form.append('file', fs.createReadStream(filePath));
    
    const response = await fetch('https://api.sha224.com/v1/file/hash', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`
      },
      body: form
    });
    
    const result = await response.json();
    console.log('File hash result:', result.hash);
    return result.hash;
  } catch (error) {
    console.error('API error:', error);
  }
}
// Streaming data example

// Browser-side chunked processing
async function processLargeFileInChunks(file, chunkSize = 1024 * 1024) {
  return new Promise((resolve, reject) => {
    const hasher = new SHA224Class();
    const fileReader = new FileReader();
    let offset = 0;
    
    // Process the file in chunks
    const readNextChunk = () => {
      const slice = file.slice(offset, offset + chunkSize);
      fileReader.readAsArrayBuffer(slice);
    };
    
    fileReader.onload = (e) => {
      // Update hash with this chunk
      const chunk = new Uint8Array(e.target.result);
      hasher.update(chunk);
      
      // Move to next chunk or finish
      offset += chunk.length;
      if (offset < file.size) {
        // Read next chunk
        readNextChunk();
      } else {
        // We've processed the entire file
        const hash = hasher.digest();
        resolve(hash);
      }
    };
    
    fileReader.onerror = (e) => {
      reject(new Error('Error reading file'));
    };
    
    // Start reading
    readNextChunk();
  });
}

// Node.js streaming example
function hashFileStream(filePath) {
  const fs = require('fs');
  const hasher = new SHA224Class();
  
  return new Promise((resolve, reject) => {
    const stream = fs.createReadStream(filePath);
    
    stream.on('data', (chunk) => {
      hasher.update(chunk);
    });
    
    stream.on('end', () => {
      const hash = hasher.digest();
      resolve(hash);
    });
    
    stream.on('error', (err) => {
      reject(err);
    });
  });
}
// HMAC example

// REST API HMAC generation
async function generateHMAC(message, key) {
  const apiKey = 'YOUR_API_KEY';
  
  try {
    const response = await fetch('https://api.sha224.com/v1/hmac', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        data: message,
        key: key,
        encoding: 'utf8',
        keyEncoding: 'utf8'
      })
    });
    
    const result = await response.json();
    console.log('HMAC result:', result.hmac);
    return result.hmac;
  } catch (error) {
    console.error('API error:', error);
  }
}

// Node.js HMAC implementation
function generateHMACNodeJS(message, key) {
  const crypto = require('crypto');
  
  const hmac = crypto.createHmac('sha224', key);
  hmac.update(message);
  return hmac.digest('hex');
}

Advanced Usage

Optimal Performance Strategies

When working with SHA-224 in performance-critical applications, consider the following best practices:

Use Chunked Processing for Large Data

For files or data streams larger than a few MB, use the chunked processing approach to avoid memory issues and maintain UI responsiveness in browser environments.

const hasher = new SHA224Class();
// Process data in manageable chunks
for (const chunk of dataChunks) {
  hasher.update(chunk);
}
const hash = hasher.digest();

Web Workers for Browser Applications

Use Web Workers to move hash computation off the main thread for browser applications, preventing UI freezing during computation.

// In main script
const hashWorker = new Worker('hash-worker.js');

hashWorker.onmessage = function(e) {
  console.log('Hash result:', e.data.hash);
};

hashWorker.postMessage({
  action: 'hash',
  data: 'Data to hash'
});

// In hash-worker.js
importScripts('https://cdn.sha224.com/js/sha224.min.js');

self.onmessage = function(e) {
  if (e.data.action === 'hash') {
    const hash = SHA224(e.data.data);
    self.postMessage({ hash });
  }
};

Binary Input for Better Performance

When possible, work directly with binary data (Uint8Array) rather than strings to avoid unnecessary encoding/decoding operations.

// More efficient to pass binary data directly
const binaryData = new Uint8Array([...]);
const hash = SHA224(binaryData);

Multihash Format Support

For interoperability with systems that use Multihash format (such as IPFS), you can convert SHA-224 hashes to Multihash format:

function sha224ToMultihash(hexHash) {
  // SHA-224 multihash prefix (0x1C = 28 in decimal)
  const prefix = '0x1C';
  // Length of SHA-224 digest in bytes (28)
  const length = '0x1C';
  
  // Convert hex hash to multihash
  return '0x' + prefix.slice(2) + length.slice(2) + hexHash;
}

// Example
const hexHash = SHA224('Hello, world!');
const multihash = sha224ToMultihash(hexHash);
console.log('Multihash:', multihash);

Custom Hash Formats

For specialized applications, you may need to format the hash output differently:

Truncated Hashing

function truncatedSHA224(message, bytes = 16) {
  // Generate full hash
  const fullHash = SHA224(message);
  
  // Truncate to specified number of bytes (multiplied by 2 for hex representation)
  return fullHash.substring(0, bytes * 2);
}

// Example: 16-byte (32 character) truncated hash
const shortHash = truncatedSHA224('Hello, world!', 16);
console.log('Truncated hash:', shortHash);

Base62 Encoding

function base62EncodeSHA224(message) {
  // First generate the standard hex hash
  const hexHash = SHA224(message);
  
  // Convert to a number (BigInt to handle the large value)
  const hashInt = BigInt('0x' + hexHash);
  
  // Define the Base62 character set
  const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  
  // Convert to Base62
  let result = '';
  let value = hashInt;
  
  while (value > 0) {
    result = charset[Number(value % 62n)] + result;
    value = value / 62n;
  }
  
  return result;
}

Ready to Implement SHA-224?

Try our interactive hash calculator or start integrating SHA-224 into your application today.