Generate SRI Hash with SHA-256
Generate a Subresource Integrity hash using the SHA-256 algorithm. Learn when SHA-256 is appropriate for SRI and how it compares to SHA-384 and SHA-512 in practice.
Detailed Explanation
SRI with SHA-256
SHA-256 is a member of the SHA-2 family of cryptographic hash functions. It produces a 256-bit (32-byte) digest, which is Base64-encoded for use in SRI integrity attributes. The resulting attribute value looks like:
integrity="sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE="
How SHA-256 Works for SRI
The generation process is straightforward:
- Fetch the complete file content (JavaScript or CSS)
- Compute the SHA-256 digest of the raw bytes
- Base64-encode the binary hash
- Prefix with
sha256-
In the browser, the Web Crypto API provides native SHA-256 support:
const data = new TextEncoder().encode(fileContent);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
const base64 = btoa(String.fromCharCode(...new Uint8Array(hashBuffer)));
const integrity = `sha256-${base64}`;
SHA-256 vs. SHA-384 for SRI
While SHA-256 is cryptographically secure and widely used for file checksums, the SRI specification recommends SHA-384 as the default algorithm. SHA-384 offers a larger digest (384 bits vs. 256 bits), providing a greater margin of security against length-extension attacks — though neither algorithm has been practically broken.
When to Choose SHA-256
- Compatibility: SHA-256 is the most universally supported hash algorithm. Every browser, every tool, and every library supports it.
- Existing workflows: If your build pipeline already generates SHA-256 checksums, reusing them for SRI avoids adding another hash computation step.
- Multiple hash fallback: You can specify multiple hashes —
sha256-...andsha384-...— in a single integrity attribute. The browser will use the strongest one it supports.
Performance Considerations
SHA-256 is marginally faster to compute than SHA-384 on 32-bit systems, but the difference is negligible for typical JavaScript and CSS file sizes (usually under 500 KB). On 64-bit systems, SHA-384 is often faster because it is based on SHA-512's internal structure, which uses 64-bit operations.
Use Case
SHA-256 SRI hashes are ideal when you need compatibility with legacy tooling, when your CI/CD pipeline already produces SHA-256 checksums for artifacts, or when you want to provide a multi-algorithm fallback alongside SHA-384. Many npm packages and CDN providers publish SHA-256 checksums alongside their releases.