SHA-224 Quick Start Guide

What is SHA-224?

SHA-224 is a cryptographic hash function that produces a 224-bit (28-byte) hash value. It's part of the SHA-2 family developed by the NSA and published by NIST. Like other hash functions, SHA-224 takes an input of arbitrary length and produces a fixed-length output, making it useful for data integrity verification, digital signatures, and other cryptographic applications.

Fixed Output Length

Always produces a 224-bit (28-byte) hash, typically represented as a 56-character hexadecimal string.

Deterministic

The same input will always produce the same output hash.

Collision Resistant

It's computationally infeasible to find two different inputs that produce the same hash output.

Pre-image Resistant

Given a hash value, it's practically impossible to determine the original input.

Getting Started with SHA-224

This guide will help you quickly implement SHA-224 hashing in your application. We'll cover the most common programming languages and provide working examples that you can copy and use right away.

JavaScript Implementation

Option 1: Node.js Built-in Crypto Module


// For Node.js environments
const crypto = require('crypto');

function generateSHA224Hash(input) {
  // Convert string to Buffer if it's not already a Buffer
  const data = typeof input === 'string' ? Buffer.from(input) : input;
  
  // Generate the hash
  return crypto.createHash('sha224').update(data).digest('hex');
}

// Example usage
const hash = generateSHA224Hash('Hello, world!');
console.log('SHA-224 hash:', hash);
// Output: SHA-224 hash: 8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568
              

Option 2: Browser Environment using SHA224.com Library


<!-- Include our SHA-224 library -->
<script src="https://cdn.sha224.com/js/sha224.min.js"></script>

<script>
  // Use the library in browser
  document.addEventListener('DOMContentLoaded', function() {
    // Generate a hash
    const hash = SHA224('Hello, world!');
    console.log('SHA-224 hash:', hash);
    
    // Or use the class-based approach
    const hasher = new SHA224();
    const hashResult = hasher.update('Hello, world!').digest('hex');
    console.log('SHA-224 hash (class method):', hashResult);
  });
</script>
              

Option 3: Using a Third-party Library (js-sha224)


// Install with: npm install js-sha224
// Or include https://cdn.jsdelivr.net/npm/[email protected]/src/sha224.min.js

// CommonJS
const sha224 = require('js-sha224');

// ES Modules
// import sha224 from 'js-sha224';

// Generate a hash
const hash = sha224('Hello, world!');
console.log('SHA-224 hash:', hash);

// For streaming data
const sha224Stream = sha224.create();
sha224Stream.update('Hello');
sha224Stream.update(', ');
sha224Stream.update('world!');
console.log('SHA-224 hash (streaming):', sha224Stream.hex());
              

Verifying a Hash


function verifySHA224Hash(input, expectedHash) {
  const calculatedHash = generateSHA224Hash(input);
  
  // Use constant-time comparison for security-critical applications
  // This simple equality check is suitable for basic use cases
  return calculatedHash === expectedHash.toLowerCase();
}

// Example usage
const isValid = verifySHA224Hash(
  'Hello, world!', 
  '8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568'
);
console.log('Hash verification result:', isValid ? 'Valid' : 'Invalid');
              

Python Implementation

Option 1: Using Python's hashlib (Recommended)


import hashlib

def generate_sha224_hash(input_data):
    # Convert input to bytes if it's a string
    if isinstance(input_data, str):
        input_data = input_data.encode('utf-8')
    
    # Generate the hash
    return hashlib.sha224(input_data).hexdigest()

# Example usage
hash_value = generate_sha224_hash('Hello, world!')
print(f'SHA-224 hash: {hash_value}')
# Output: SHA-224 hash: 8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568

# For chunked/streaming data
def generate_sha224_hash_chunked(data_chunks):
    hasher = hashlib.sha224()
    for chunk in data_chunks:
        if isinstance(chunk, str):
            chunk = chunk.encode('utf-8')
        hasher.update(chunk)
    return hasher.hexdigest()

# Example with chunked data
chunks = ['Hello', ', ', 'world', '!']
hash_value = generate_sha224_hash_chunked(chunks)
print(f'SHA-224 hash (chunked): {hash_value}')
              

Option 2: Using SHA224.com Python SDK


# Install with: pip install sha224-sdk
from sha224_sdk import SHA224Client

# Initialize the client (no API key needed for local operations)
client = SHA224Client()

# Generate a hash
hash_value = client.generate_hash('Hello, world!')
print(f'SHA-224 hash: {hash_value}')

# Verify a hash
is_valid = client.verify_hash(
    'Hello, world!',
    '8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568'
)
print(f'Hash verification result: {"Valid" if is_valid else "Invalid"}')
              

Handling Files


import hashlib

def generate_file_sha224(file_path):
    """Generate SHA-224 hash for a file"""
    hasher = hashlib.sha224()
    with open(file_path, 'rb') as f:
        # Read and update hash in chunks of 4K
        for chunk in iter(lambda: f.read(4096), b''):
            hasher.update(chunk)
    return hasher.hexdigest()

# Example usage
file_hash = generate_file_sha224('document.pdf')
print(f'File SHA-224 hash: {file_hash}')

def verify_file_integrity(file_path, expected_hash):
    """Verify file integrity using SHA-224 hash"""
    calculated_hash = generate_file_sha224(file_path)
    return calculated_hash == expected_hash.lower()

# Example usage
is_valid = verify_file_integrity(
    'document.pdf',
    '7c5ef6ce3ae40c0d2a917a4dc21742086c01f72d6c72cb85e6941189'
)
print(f'File integrity check: {"Passed" if is_valid else "Failed"}')
              

Java Implementation

Option 1: Using Java's MessageDigest


import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;

public class SHA224Example {
    public static String generateSHA224Hash(String input) throws Exception {
        // Create MessageDigest instance for SHA-224
        MessageDigest md = MessageDigest.getInstance("SHA-224");
        
        // Calculate digest
        byte[] hashBytes = md.digest(input.getBytes(StandardCharsets.UTF_8));
        
        // Convert to hex string
        StringBuilder hexString = new StringBuilder();
        for (byte b : hashBytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        
        return hexString.toString();
    }
    
    // Alternative implementation with BigInteger
    public static String generateSHA224HashAlt(String input) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-224");
        byte[] hashBytes = md.digest(input.getBytes(StandardCharsets.UTF_8));
        
        // Convert to hex using BigInteger
        BigInteger number = new BigInteger(1, hashBytes);
        StringBuilder hexString = new StringBuilder(number.toString(16));
        
        // Ensure leading zeros are included
        while (hexString.length() < 56) {
            hexString.insert(0, '0');
        }
        
        return hexString.toString();
    }
    
    public static boolean verifySHA224Hash(String input, String expectedHash) throws Exception {
        String calculatedHash = generateSHA224Hash(input);
        return calculatedHash.equalsIgnoreCase(expectedHash);
    }
    
    public static void main(String[] args) {
        try {
            String input = "Hello, world!";
            String hash = generateSHA224Hash(input);
            System.out.println("SHA-224 hash: " + hash);
            
            boolean isValid = verifySHA224Hash(
                input, 
                "8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568"
            );
            System.out.println("Hash verification result: " + (isValid ? "Valid" : "Invalid"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
              

Option 2: Using SHA224.com Java SDK


// Add dependency: com.sha224:sha224-sdk:1.0.0

import com.sha224.sdk.SHA224Client;
import com.sha224.sdk.exception.SHA224Exception;

public class SHA224SDKExample {
    public static void main(String[] args) {
        // Initialize the client
        SHA224Client client = new SHA224Client();
        
        try {
            // Generate a hash
            String hash = client.generateHash("Hello, world!");
            System.out.println("SHA-224 hash: " + hash);
            
            // Verify a hash
            boolean isValid = client.verifyHash(
                "Hello, world!", 
                "8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568"
            );
            System.out.println("Hash verification result: " + (isValid ? "Valid" : "Invalid"));
        } catch (SHA224Exception e) {
            e.printStackTrace();
        }
    }
}
              

Processing Files and Streams


import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA224FileExample {
    public static String generateFileSHA224(String filePath) throws NoSuchAlgorithmException, IOException {
        MessageDigest md = MessageDigest.getInstance("SHA-224");
        FileInputStream fis = new FileInputStream(filePath);
        
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            md.update(buffer, 0, bytesRead);
        }
        fis.close();
        
        byte[] hashBytes = md.digest();
        
        // Convert to hex string
        StringBuilder sb = new StringBuilder();
        for (byte b : hashBytes) {
            sb.append(String.format("%02x", b));
        }
        
        return sb.toString();
    }
    
    public static boolean verifyFileIntegrity(String filePath, String expectedHash) 
            throws NoSuchAlgorithmException, IOException {
        String calculatedHash = generateFileSHA224(filePath);
        return calculatedHash.equalsIgnoreCase(expectedHash);
    }
    
    public static void main(String[] args) {
        try {
            String filePath = "document.pdf";
            String hash = generateFileSHA224(filePath);
            System.out.println("File SHA-224 hash: " + hash);
            
            boolean isValid = verifyFileIntegrity(
                filePath,
                "7c5ef6ce3ae40c0d2a917a4dc21742086c01f72d6c72cb85e6941189"
            );
            System.out.println("File integrity check: " + (isValid ? "Passed" : "Failed"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
              

Go Implementation

Option 1: Using Go's crypto/sha256 Package


package main

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"os"
	"strings"
)

// GenerateSHA224Hash returns the SHA-224 hash of the input string
func GenerateSHA224Hash(input string) string {
	// SHA-224 is a truncated version of SHA-256
	hash := sha256.Sum224([]byte(input))
	return hex.EncodeToString(hash[:])
}

// VerifySHA224Hash checks if the input string produces the expected hash
func VerifySHA224Hash(input, expectedHash string) bool {
	calculatedHash := GenerateSHA224Hash(input)
	return strings.EqualFold(calculatedHash, expectedHash)
}

// GenerateFileSHA224Hash calculates the SHA-224 hash of a file
func GenerateFileSHA224Hash(filePath string) (string, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	// Use New224 to create SHA-224 hash
	hash := sha256.New224()
	
	// Copy the file data into the hash
	if _, err := io.Copy(hash, file); err != nil {
		return "", err
	}
	
	// Get the hash result
	hashBytes := hash.Sum(nil)
	return hex.EncodeToString(hashBytes), nil
}

func main() {
	// Basic string hashing
	input := "Hello, world!"
	hash := GenerateSHA224Hash(input)
	fmt.Printf("SHA-224 hash: %s\n", hash)
	
	// Verify a hash
	isValid := VerifySHA224Hash(
		input,
		"8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568",
	)
	fmt.Printf("Hash verification result: %t\n", isValid)
	
	// File hashing example
	filePath := "document.pdf"
	fileHash, err := GenerateFileSHA224Hash(filePath)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}
	fmt.Printf("File SHA-224 hash: %s\n", fileHash)
}
              

Option 2: Streaming/Chunked Data


package main

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
)

// StreamingSHA224 represents a streaming SHA-224 hash
type StreamingSHA224 struct {
	hash sha256.Hash
}

// NewStreamingSHA224 creates a new streaming SHA-224 hash
func NewStreamingSHA224() *StreamingSHA224 {
	return &StreamingSHA224{
		hash: *sha256.New224(),
	}
}

// Update adds data to the hash
func (s *StreamingSHA224) Update(data []byte) {
	s.hash.Write(data)
}

// Digest returns the final hash value as a hex string
func (s *StreamingSHA224) Digest() string {
	hashBytes := s.hash.Sum(nil)
	return hex.EncodeToString(hashBytes)
}

func main() {
	// Create a new streaming hash
	hasher := NewStreamingSHA224()
	
	// Add data in chunks
	hasher.Update([]byte("Hello"))
	hasher.Update([]byte(", "))
	hasher.Update([]byte("world"))
	hasher.Update([]byte("!"))
	
	// Get the final hash
	hash := hasher.Digest()
	fmt.Printf("Streaming SHA-224 hash: %s\n", hash)
}
              

Ruby Implementation

Option 1: Using Ruby's Digest Library


require 'digest'

# Generate a SHA-224 hash
def generate_sha224_hash(input)
  Digest::SHA2.new(224).hexdigest(input)
end

# Verify a SHA-224 hash
def verify_sha224_hash(input, expected_hash)
  calculated_hash = generate_sha224_hash(input)
  calculated_hash.downcase == expected_hash.downcase
end

# Example usage
input = "Hello, world!"
hash = generate_sha224_hash(input)
puts "SHA-224 hash: #{hash}"

# Verify a hash
is_valid = verify_sha224_hash(
  input,
  "8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568"
)
puts "Hash verification result: #{is_valid ? 'Valid' : 'Invalid'}"
              

Option 2: File Hashing


require 'digest'

# Generate SHA-224 hash for a file
def generate_file_sha224(file_path)
  Digest::SHA2.file(file_path, 224).hexdigest
end

# Verify file integrity using SHA-224 hash
def verify_file_integrity(file_path, expected_hash)
  calculated_hash = generate_file_sha224(file_path)
  calculated_hash.downcase == expected_hash.downcase
end

# Example usage
file_path = "document.pdf"
hash = generate_file_sha224(file_path)
puts "File SHA-224 hash: #{hash}"

# Verify file integrity
is_valid = verify_file_integrity(
  file_path,
  "7c5ef6ce3ae40c0d2a917a4dc21742086c01f72d6c72cb85e6941189"
)
puts "File integrity check: #{is_valid ? 'Passed' : 'Failed'}"
              

Option 3: Streaming/Chunked Data


require 'digest'

# Generate SHA-224 hash for chunked data
def generate_chunked_sha224(chunks)
  digest = Digest::SHA2.new(224)
  chunks.each { |chunk| digest.update(chunk) }
  digest.hexdigest
end

# Example usage
chunks = ["Hello", ", ", "world", "!"]
hash = generate_chunked_sha224(chunks)
puts "Chunked SHA-224 hash: #{hash}"
              

PHP Implementation

Option 1: Using PHP's hash Function


<?php
// Generate a SHA-224 hash
function generateSHA224Hash($input) {
    return hash('sha224', $input);
}

// Verify a SHA-224 hash
function verifySHA224Hash($input, $expectedHash) {
    $calculatedHash = generateSHA224Hash($input);
    return strtolower($calculatedHash) === strtolower($expectedHash);
}

// Example usage
$input = "Hello, world!";
$hash = generateSHA224Hash($input);
echo "SHA-224 hash: " . $hash . PHP_EOL;

// Verify a hash
$isValid = verifySHA224Hash(
    $input,
    "8552d8b7a7dc5476cb9e25dee69a8091290764b7f2a64fe6e78e9568"
);
echo "Hash verification result: " . ($isValid ? "Valid" : "Invalid") . PHP_EOL;
?>
              

Option 2: File Hashing


<?php
// Generate SHA-224 hash for a file
function generateFileSHA224($filePath) {
    return hash_file('sha224', $filePath);
}

// Verify file integrity using SHA-224 hash
function verifyFileIntegrity($filePath, $expectedHash) {
    $calculatedHash = generateFileSHA224($filePath);
    return strtolower($calculatedHash) === strtolower($expectedHash);
}

// Example usage
$filePath = "document.pdf";
$hash = generateFileSHA224($filePath);
echo "File SHA-224 hash: " . $hash . PHP_EOL;

// Verify file integrity
$isValid = verifyFileIntegrity(
    $filePath,
    "7c5ef6ce3ae40c0d2a917a4dc21742086c01f72d6c72cb85e6941189"
);
echo "File integrity check: " . ($isValid ? "Passed" : "Failed") . PHP_EOL;
?>
              

Option 3: Using hash_init for Streaming/Chunked Data


<?php
// Generate SHA-224 hash for chunked data
function generateChunkedSHA224($chunks) {
    $context = hash_init('sha224');
    foreach ($chunks as $chunk) {
        hash_update($context, $chunk);
    }
    return hash_final($context);
}

// Example usage
$chunks = ["Hello", ", ", "world", "!"];
$hash = generateChunkedSHA224($chunks);
echo "Chunked SHA-224 hash: " . $hash . PHP_EOL;
?>
              

Common Use Cases

Data Integrity Verification

Ensure data hasn't been corrupted or tampered with during storage or transmission by comparing hashes.


// Check if a downloaded file matches the expected hash
function verifyDownload(filePath, expectedHash) {
  const fileHash = generateFileSHA224(filePath);
  if (fileHash === expectedHash) {
    console.log('Download verified successfully');
    return true;
  } else {
    console.error('Download verification failed');
    return false;
  }
}
              

De-duplication

Use SHA-224 hashes to identify duplicate data for efficient storage and caching.


# Simple de-duplication system
class Deduplicator:
    def __init__(self):
        self.content_store = {}
        
    def store(self, data):
        """Store data and return its hash identifier"""
        data_hash = generate_sha224_hash(data)
        
        # Only store if we don't already have this content
        if data_hash not in self.content_store:
            self.content_store[data_hash] = data
            
        return data_hash
        
    def retrieve(self, data_hash):
        """Retrieve content by its hash"""
        if data_hash in self.content_store:
            return self.content_store[data_hash]
        return None
              

Content Addressing

Use SHA-224 hashes as content identifiers in distributed systems or content-addressed storage.


class ContentStore {
  constructor(basePath) {
    this.basePath = basePath;
    // Ensure directory exists
  }
  
  async store(content) {
    const hash = generateSHA224Hash(content);
    const path = `${this.basePath}/${hash}`;
    // Write content to path
    return hash;
  }
  
  async retrieve(hash) {
    const path = `${this.basePath}/${hash}`;
    // Read content from path
    return content;
  }
}
              

Best Practices

Do: Use Standard Libraries

Whenever possible, use your language's standard cryptographic libraries rather than implementing the algorithm yourself. These libraries are typically well-tested and optimized.

Do: Verify Hashes Securely

For security-sensitive applications, use constant-time comparison when verifying hashes to prevent timing attacks.

Do: Process Large Files in Chunks

When hashing large files, process them in chunks rather than loading the entire file into memory. Most crypto libraries provide streaming/updating interfaces for this purpose.

Don't: Use for Password Storage

SHA-224 (like all general-purpose hash functions) is not suitable for storing passwords. Use specialized password hashing algorithms like Argon2, bcrypt, or PBKDF2 instead.

Don't: Expose Secret Keys in Hashes

Don't include sensitive information like API keys or passwords as part of strings being hashed, unless you're using HMAC or another authenticated hashing technique.

Next Steps

Ready to Try SHA-224?

Experiment with our interactive hash calculator to see SHA-224 in action.

Try the Hash Calculator