How to Calculate SHA-256 vs SHA-384 for SRI

Implementation Guide for Secure Asset Delivery

Subresource Integrity (SRI) provides a cryptographic guarantee that third-party or CDN-hosted assets execute exactly as authored. The browser fetch pipeline intercepts resource responses before execution. Hash validation occurs client-side post-download but pre-parse. This mechanism does not mitigate compromised origin servers or active TLS interception. It strictly relies on immutable asset delivery and enforced CORS preflight for cross-origin resources.

Selecting between SHA-256 and SHA-384 depends on your threat model and regulatory posture. SHA-256 delivers 128-bit collision resistance. It satisfies baseline OWASP recommendations and standard web application requirements. SHA-384 provides 192-bit security. It aligns with stricter federal mandates and high-assurance environments. For detailed cryptographic trade-offs, review Understanding Cryptographic Hash Algorithms before standardizing your pipeline.

CLI & Programmatic Hash Generation

OpenSSL, Node.js, Python, and Bash Workflows

Generating valid SRI digests requires strict binary-to-text conversion pipelines. ASCII encoding prior to base64 conversion produces invalid hashes. Browsers immediately reject malformed tokens. Always operate on raw binary output.

OpenSSL CLI Pipe the binary digest directly into base64 encoding without line wrapping:

openssl dgst -sha384 -binary asset.js | openssl base64 -A

The -A flag suppresses newline characters. This ensures a continuous string compatible with HTML attributes.

Node.js Crypto Module Leverage the native crypto module for programmatic generation within build scripts:

const fs = require('fs');
const crypto = require('crypto');
const buffer = fs.readFileSync('asset.js');
const hash = crypto.createHash('sha256').update(buffer).digest('base64');
console.log(`sha256-${hash}`);

Python 3 Workflow

import hashlib, base64
with open('asset.js', 'rb') as f:
    digest = hashlib.sha384(f.read()).digest()
    print(f"sha384-{base64.b64encode(digest).decode('utf-8')}")

Validate cross-platform parity by comparing outputs across environments. Minor whitespace differences in line endings will invalidate the digest.

Base64 Encoding & SRI Attribute Formatting

Constructing Valid integrity="sha256-..." Tokens

The integrity attribute requires a specific token structure: <algorithm>-<base64-digest>. Browsers parse this string before initiating network requests. Whitespace inside the token breaks validation.

Multi-hash concatenation allows graceful algorithm migration:

<script src="https://cdn.vendor.com/lib.js"
  integrity="sha256-abc123... sha384-def456..."
  crossorigin="anonymous"></script>

The browser evaluates hashes left-to-right. The first match satisfies the constraint. Always separate tokens with a single space.

Omitting crossorigin="anonymous" on third-party assets triggers CORS preflight failures. The browser will block the request entirely. This behavior bypasses SRI validation but prevents execution. The fetch abort mechanics are detailed in Core SRI Fundamentals & Browser Security Boundaries.

Build Pipeline & CI/CD Integration

Automating SRI in Webpack, Vite, and GitHub Actions

Manual hash injection introduces human error. It breaks continuous delivery workflows. Integrate SRI generation directly into asset compilation.

Webpack Configuration Use webpack-subresource-integrity for automated injection:

const SriPlugin = require('webpack-subresource-integrity');
module.exports = {
  plugins: [
    new SriPlugin({
      hashFuncNames: ['sha256', 'sha384'],
      enabled: process.env.NODE_ENV === 'production'
    })
  ]
};

CI/CD Validation Gate Implement a pre-deploy integrity check in GitHub Actions:

- name: Verify SRI Hashes
  run: |
    npm run build
    node scripts/verify-sri.js

The verification script should parse generated HTML. It must extract integrity values, recalculate digests from the dist/ directory, and fail the pipeline on mismatch. This enforces supply chain hardening before assets reach edge caches.

Validation & Browser Enforcement Testing

DevTools Console Analysis & Automated QA

Browser enforcement is strict. A single bit mismatch triggers a hard block. The resource downloads fully, fails the hash check, and aborts execution.

DevTools Console Signatures Expect the following exact error format when validation fails:

Failed to find a valid digest in the 'integrity' attribute for resource 'https://cdn.vendor.com/lib.js' with computed SHA-256 integrity 'sha256-xyz...'. The resource has been blocked.

Network waterfall analysis shows a 200 OK response. The script tag remains unexecuted. Use the Network tab to verify response headers and payload size.

Automated QA Strategy Inject a deliberate hash mismatch in staging environments. Verify that Puppeteer or Playwright captures the console error. This confirms your fallback routing logic activates correctly.

Compliance Mapping & Audit Documentation

SOC 2, ISO 27001, and NIST Alignment

Auditors require evidence of cryptographic asset verification. Maintain a version-controlled sri-manifest.json alongside deployment artifacts.

Map algorithm selection to regulatory baselines:

  • SOC 2 Type II: Document automated hash regeneration and CI/CD gates.
  • ISO 27001 (A.14.2.5): Prove secure development lifecycle integration.
  • NIST SP 800-53 (SC-8): Align SHA-384 usage with transmission confidentiality controls.

Store manifests in Git with cryptographic commit signing. Include pipeline logs showing successful validation runs. This creates an immutable audit trail for compliance reviews.

Production Fallback & Rollback Paths

Implement build-time hash regeneration on every asset update. Configure CDN edge rules to serve fallback versions if integrity mismatch triggers. Use CSP script-src-elem with unsafe-inline strictly as a temporary development bypass. Deploy automated CI/CD integrity checks to catch drift before production deployment.

If a vendor rotates keys unexpectedly, route traffic through a reverse proxy. Strip SRI attributes temporarily while you regenerate hashes. This maintains availability while preserving security posture during incident response.

Common Pitfalls & Engineering Mitigations

  • ASCII vs Binary Encoding: Always pipe raw binary output to base64. Never encode text strings.
  • Missing crossorigin: Enforce crossorigin="anonymous" on all <script> and <link> tags.
  • Hardcoded Static Hashes: Automate regeneration via build plugins. Never edit HTML manually.
  • Compliance Algorithm Mismatch: Audit regulatory requirements before selecting SHA-256. Upgrade to SHA-384 for high-assurance workloads.
  • Whitespace/Minification Drift: Calculate hashes against the exact artifact served by the CDN. Never hash local unminified source.
Understanding Cryptographic Hash Algorithms Core SRI Fundamentals & Browse…