hash package provides interfaces for hash functions. It contains subpackages implementing various hash algorithms.
Core Interface
Subpackages
hash/crc32
CRC-32 checksums (IEEE and Castagnoli polynomials).hash/crc64
CRC-64 checksums.hash/fnv
FNV-1 and FNV-1a hash functions.hash/adler32
Adler-32 checksum.hash/maphash
Fast, non-cryptographic hash for hash tables.Practical Examples
File Checksum
Verify File Integrity
Hash-based Deduplication
Hash Table with Custom Hash
Content-Addressable Storage
Hash Function Comparison
| Algorithm | Output Size | Cryptographic | Speed | Use Case |
|---|---|---|---|---|
| CRC32 | 32 bits | No | Very Fast | Error detection |
| CRC64 | 64 bits | No | Very Fast | Error detection |
| Adler32 | 32 bits | No | Very Fast | Checksums |
| FNV-1a | 32/64 bits | No | Fast | Hash tables |
| maphash | 64 bits | No | Very Fast | Hash tables (Go) |
| MD5 | 128 bits | Broken | Fast | Legacy, non-security |
| SHA-1 | 160 bits | Broken | Fast | Legacy, non-security |
| SHA-256 | 256 bits | Yes | Medium | Integrity, security |
| SHA-512 | 512 bits | Yes | Medium | Security |
Best Practices
- Choose appropriate hash - Cryptographic for security, non-cryptographic for speed
- Use crypto/sha256 - For file integrity and digital signatures
- Use hash/maphash - For hash tables and non-cryptographic hashing
- Avoid MD5/SHA-1 - For security purposes (use SHA-256+)
- Stream large files - Use io.Copy instead of loading into memory
- Reuse hash objects - Call Reset() instead of creating new instances
Common Use Cases
- File integrity: Verify downloads haven’t been corrupted
- Deduplication: Identify duplicate files by content
- Caching: Generate cache keys from content
- Hash tables: Fast lookups with maphash
- Checksums: Detect data corruption with CRC
- Content addressing: Store and retrieve by hash