Mastering Algorithms

SHA (Secure Hash Algorithm)

Overview

SHA (Secure Hash Algorithm) is a family of cryptographic hash functions designed by the National Security Agency (NSA) and published by NIST. Hash functions are one-way functions that take input data of any size and produce a fixed-size hash value (digest).

SHA algorithms are used for data integrity verification, digital signatures, password hashing, and blockchain technology. They ensure that data hasn't been tampered with by producing a unique fingerprint for any given input.

SHA Variants

Variant Output Size Block Size Status
SHA-1 160 bits 512 bits Deprecated
SHA-256 256 bits 512 bits Secure
SHA-512 512 bits 1024 bits Secure

How It Works

  1. Padding: Add padding to make input length a multiple of block size
  2. Message Schedule: Break message into blocks
  3. Compression Function: Process each block through compression rounds
  4. Final Hash: Combine all block hashes into final digest

Implementation


import hashlib

def sha256_hash(data):
    """Compute SHA-256 hash"""
    return hashlib.sha256(data.encode()).hexdigest()

def sha512_hash(data):
    """Compute SHA-512 hash"""
    return hashlib.sha512(data.encode()).hexdigest()

# Example usage
message = "Hello, SHA!"
hash_256 = sha256_hash(message)
hash_512 = sha512_hash(message)

print(f"SHA-256: {hash_256}")
print(f"SHA-512: {hash_512}")

# Verification
def verify_integrity(original, received, hash_value):
    """Verify data integrity"""
    computed_hash = sha256_hash(received)
    return computed_hash == hash_value
                

Hash Function Properties

  • Deterministic: Same input always produces same output
  • Fast Computation: Hash can be computed quickly
  • Pre-image Resistance: Hard to find input given hash
  • Collision Resistance: Hard to find two inputs with same hash
  • Avalanche Effect: Small input change causes large hash change

Applications

  • Data Integrity: Verify files haven't been modified
  • Digital Signatures: Sign documents and messages
  • Password Hashing: Store password hashes (with salt)
  • Blockchain: Bitcoin and other cryptocurrencies
  • Version Control: Git uses SHA-1 for commit hashes

Security Considerations

  • SHA-1: Deprecated, vulnerable to collision attacks
  • SHA-256: Currently secure, recommended for most uses
  • SHA-512: More secure, use for high-security applications
  • Salt: Always use salt with hash for password storage

Related Algorithms

Explore other encryption algorithms: