SRI Hash Generator

Subresource Integrity (SRI) Hash Generator

Generate SHA-256, SHA-384, and SHA-512 hashes for script or stylesheet content.

0 characters

How ZeroData protects your privacy

  • No Uploads: Tool input is processed in your browser and is not sent to ZeroData servers.
  • No Storage: Tool input is not saved by this website.
  • No Input Tracking: Analytics never receive the text, files, keys, or credentials you process.
  • Verifiable: Disconnect from the network after the page loads; local tool processing continues without uploading your input.

Quick Solution

To generate an SRI hash via the command line, use OpenSSL: openssl dgst -sha384 -binary script.js | openssl base64 -A. Then, add the output to your HTML tag: <script src="script.js" integrity="sha384-[YOUR_HASH]" crossorigin="anonymous"></script>.

When Should I Use This?

Use the SRI hash generator to protect your website from compromised third-party CDNs and supply chain attacks.

  • Loading popular libraries like React, jQuery, or Bootstrap from public CDNs safely.
  • Complying with strict Content Security Policy (CSP) requirements that mandate Subresource Integrity for all external scripts.
  • Ensuring that third-party analytics or tracking scripts cannot be maliciously modified to inject malware into your site.

Deep Dive: Subresource Integrity (SRI) & Supply Chain Defense

Modern web application architectures depend on geographically distributed Content Delivery Networks (CDNs), edge caching layers, and third-party vendor repositories to serve vendor libraries like React, Tailwind, jQuery, and analytics frameworks. However, loading external Javascript and stylesheet files directly into an application's execution context creates a severe surface area for **software supply chain attacks**. If an attacker breaches a CDN origin, hijacks a DNS routing table, or compromises a vendor asset repository, they can silently inject malicious keystroke loggers, credential stealers, or cryptomined payloads directly into thousands of dependent applications simultaneously without altering your domain servers.

**Subresource Integrity (SRI)** is a W3C web standard designed to eliminate third-party code manipulation vulnerabilities. By appending a cryptographic checksum directly to your HTML application shell via the integrity attribute, you establish a mathematical contract of trust with the end user's browser. When the client attempts to download an external file, the browser calculates the cryptographic hash of the received stream in memory prior to execution. If the computed digest diverges from your defined hash by even a single bit, the browser instantly rejects the script, throws a network error, and insulates your users from compromise.

Architectural Mechanics of W3C Integrity Verification

When an SRI-protected resource is encountered during DOM parsing, modern rendering engines execute a multi-phase verification pipeline within the networking layer:

  1. Stream Interception & Decompression: The network stack fetches the remote bundle and strips standard HTTP transport encoding headers (Gzip, Deflate, Brotli) to access the underlying plaintext binary stream.
  2. Cryptographic Digest Computation: The engine inspects the algorithm prefix (e.g., sha384-) and passes the uncompressed binary byte array into the designated hashing function using standard Merkle–Damgård or Sponge constructions.
  3. Base64 Digest Encoding: The raw hexadecimal binary output of the digest is converted into a standard Base64 encoding string to match HTML attribute syntax requirements.
  4. Bitwise Comparison Gate: The calculated string is compared against your declared attribute value. If verified, the Abstract Syntax Tree (AST) compiler begins script execution. If invalid, a fatal network security error terminates processing.

CLI Automation & Build Pipeline Integration

While web-based SRI generation utilities are indispensable for debugging single script insertions or reviewing vendor updates, modern DevSecOps practices mandate automating integrity calculation inside Continuous Integration (CI/CD) pipelines. Implementing automated bash, OpenSSL, or Node.js scripts prevents developers from manually pasting outdated script hashes when releasing production build artifacts.

1. Generating SRI Hashes via Linux & macOS OpenSSL

You can leverage native UNIX OpenSSL command-line tools to calculate SHA-384 digests directly from file paths or pipe streaming web responses from `curl`:

# Calculate SRI hash from a local static bundle file:
openssl dgst -sha384 -binary dist/bundle.min.js | openssl base64 -A | awk '{print "sha384-"$0}'

# Fetch remote CDN file directly and calculate its SRI integrity string:
curl -s https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css | openssl dgst -sha384 -binary | openssl base64 -A | sed 's/^/integrity="sha384-/;s/$/"/'

2. Node.js CI/CD Automated Integrity Script

For frontend JavaScript frameworks and automated build environments, use standard Node.js core crypto modules to dynamically generate SRI manifests during post-build phases:

import { createHash } from 'node:crypto';
import { readFileSync, writeFileSync } from 'node:fs';

function generateSRI(filePath, algorithm = 'sha384') {
  const fileBuffer = readFileSync(filePath);
  const hash = createHash(algorithm).update(fileBuffer).digest('base64');
  return `${algorithm}-${hash}`;
}

const targetFile = './dist/app.bundle.js';
const sriDigest = generateSRI(targetFile, 'sha384');
console.log(`[Build Success] Calculated SRI for ${targetFile}: ${sriDigest}`);
// Inject directly into HTML templates:
// <script src="app.bundle.js" integrity="${sriDigest}" crossorigin="anonymous"></script>

Troubleshooting SRI Verification Failures

When an integrity verification check fails, web browsers terminate asset evaluation instantly to shield users from unauthorized instructions. Below are explicit diagnostic resolutions for the most frequent runtime errors encountered when implementing Subresource Integrity in production web architectures.

Error: "Failed to find a valid digest in the 'integrity' attribute"

Root Cause: The browser detected an unrecognized algorithm prefix (e.g., attempting to use md5- or sha1-) or discovered invalid character formatting inside the Base64 sequence (such as unescaped line breaks, missing padding equals signs, or accidental trailing whitespace).

Resolution: Ensure your string starts strictly with a W3C-supported designator: sha256-, sha384-, or sha512-. Verify that no carriage returns or spaces exist within the generated hash string. Use our Base64 Encoder or Hash Generator to validate binary encoding conversions.

Error: "Subresource Integrity attribute exists, but the resource requires CORS header"

Root Cause: You attached an integrity attribute to an external third-party script URL but omitted the mandatory Cross-Origin Resource Sharing directive, or the target server refused to provide an appropriate Access-Control-Allow-Origin header in its response.

Resolution: Always append the attribute crossorigin="anonymous" whenever fetching assets across domain boundaries. If loading scripts from an internal microservices endpoint or custom S3 bucket, ensure the serving infrastructure includes proper headers using our CORS Header Generator.

Error: "Integrity check failed for resource... Expected sha384-XXX but computed sha384-YYY"

Root Cause: The exact raw binary bytes delivered by the server diverged from the bytes used to calculate your initial digest string. This is frequently triggered by edge servers applying auto-minification, version tags floating to new releases (e.g., referencing @latest instead of pinned semantic versions), or operating system line ending conversions (CRLF vs LF) during Git deployments.

Resolution: Lock all CDN script tags to exact semantic release versions. Avoid referencing dynamic release aliases. Ensure that your reverse proxy and edge caching layers (such as Cloudflare or AWS CloudFront) do not automatically re-compress or inject tracking tokens into vendor asset distributions. For secure header hardening, review our Security Headers Builder and Web Security Complete Guide.

Enterprise Privacy & Zero-Upload Guarantee

When securing proprietary web software, corporate internal tooling, or unreleased commercial applications, exposing production source code to cloud conversion endpoints represents a severe data leakage hazard. Conventional online utilities transmit pasted code files over public networks to backend servers for analysis, risking exposure to server log interception, network interception, or third-party training pipelines.

ZeroData Tools operates on an unconditional zero-upload architectural promise. When you generate cryptographic digests with this tool, all calculations execute entirely on your machine using your browser's native hardware-accelerated Web Crypto API. No source code scripts, CSS stylesheets, or resulting cryptographic hash values ever cross your network interface, touch external databases, or get recorded in telemetry servers. Your intellectual property remains strictly confined to your local hardware.

How to Use the SRI Hash Generator

  1. Paste Script or Stylesheet Payload: Insert the exact raw text contents of your target Javascript (.js) or Cascading Stylesheet (.css) file directly into the editor pane.
  2. Choose Cryptographic Algorithm: Select your targeted Secure Hash Algorithm. We recommend SHA-384 as standard W3C best practice for high collision resistance and optimal performance.
  3. Configure Cross-Origin Resource Sharing: Toggle whether the generated HTML attribute string should attach the mandatory crossorigin="anonymous" parameter for CDN-fetched files.
  4. Compute Cryptographic Digest: The utility instantly triggers your browser's hardware-accelerated Web Crypto API to generate a standard Base64-encoded binary hash prefix.
  5. Copy & Deploy Integrity Attribute: Copy the generated HTML <script> or <link> snippet and integrate it directly into your application root layout or continuous deployment template.

Common Use Cases

  • Securing Content Delivery Networks (CDNs): Shielding production web applications from software supply chain attacks where hostile threat actors compromise public CDNs (like cdnjs, jsDelivr, or unpkg) to silently distribute skimmer scripts or cryptominers.
  • Achieving PCI DSS v4.0 & SOC 2 Compliance: Meeting strict Payment Card Industry requirements (Specifically Requirement 6.4.3 and 11.6.1) requiring continuous script integrity monitoring, tamper defense, and cryptographic validation on payment checkout pages.
  • Auditing Third-Party Analytics & Marketing Pixels: Verifying that third-party customer support widgets, analytics wrappers, and external tracking bundles match exact approved checksums before granting access to document DOM trees.
  • Zero-Trust Edge Application Deployment: Protecting enterprise applications deployed across distributed multi-cloud architectures by cryptographically validating frontend static assets regardless of which untrusted edge relay served the response.
  • Verifying Open-Source Library Reproducibility: Providing mathematical verification to developers and auditor teams that bundled production vendor dependencies correspond precisely to open-source GitHub release tags without undocumented modifications.

Frequently Asked Questions

How does Subresource Integrity (SRI) verify scripts and stylesheets in real time?

When a browser encounters a script or stylesheet tag containing an integrity attribute, its network stack suspends evaluation while streaming the incoming binary body. The networking engine runs the designated hash function (e.g., SHA-384) over the uncompressed binary bytes. It then Base64-encodes the computed output and compares it character-for-character against your declared hash string. If they differ by even a single bit, the browser aborts execution with a syntax error, preventing tampered code from running.

Why does SRI require the crossorigin="anonymous" attribute for external scripts?

By default, Cross-Origin Resource Sharing (CORS) security rules prevent browsers from exposing raw contents or cryptographic properties of resources hosted on third-party domains (such as CDNs) to protect against cross-origin data theft. Adding crossorigin="anonymous" forces the browser to issue a CORS fetch request without credentials. If the CDN returns an Access-Control-Allow-Origin header matching your domain or *, the browser is permitted to read the payload bytes and evaluate the cryptographic integrity digest.

Why does the W3C strongly recommend SHA-384 over SHA-256 or SHA-512 for SRI attributes?

The W3C recommends SHA-384 as the optimal default because it offers exceptional cryptographic collision resistance without burdening HTML payloads with unnecessary character bloat. While SHA-256 is mathematically secure against brute-force pre-image attacks today, SHA-384 doubles the bitwise security buffer against future quantum-assisted attacks while generating an 88-character attribute—striking an ideal balance between long-term cryptographic durability and HTML document transmission speed.

Why did my SRI hash break after enabling Cloudflare Auto-Minify, Gzip, or Brotli compression?

HTTP compression protocols like Gzip (gzip), Brotli (br), and Deflate operate entirely at the Transport Layer (Layer 4/7 boundary); the browser automatically decompresses the incoming payload before calculating the SRI hash. However, if an intermediary network edge tool (such as Cloudflare Auto-Minify, dynamic asset injection, or responsive ad wrappers) alters the actual source character syntax—such as stripping comments, stripping whitespace, or altering line endings from CRLF to LF—the raw uncompressed binary alters completely, causing verification to fail.

Can I generate SRI hash tags for static image formats, video streams, or font files?

No. Under the current W3C Subresource Integrity specification (SRI Level 1 and Level 2 draft), the integrity attribute is explicitly supported exclusively for elements that fetch executable code or cascading styles: <script> and <link rel="stylesheet"> tags. Browsers do not currently process integrity checks on <img>, <video>, <audio>, or CSS @font-face rules.

How can I specify multiple backup algorithm hashes inside a single integrity attribute?

You can safely specify multiple space-delimited cryptographic hashes inside one integrity string (e.g., integrity="sha256-... sha384-... sha512-..."). Modern Chromium and Firefox browsers analyze all supplied prefixes and evaluate ONLY the strongest algorithm available (ignoring SHA-256 if SHA-384 or SHA-512 is present). This provides backward-compatible fallback capabilities for legacy client runtimes that may lack support for newer SHA-2 cryptographic suites.

What happens if a CDN vendor suffers an outage or revokes access to the integrity asset?

SRI exclusively protects against data modification and supply chain injection; it does not solve high availability or uptime faults. If an external CDN experiences a routing failure or returns an error page (like a 502 Bad Gateway or 404 Not Found), the returned error HTML will fail the SRI hash check and block execution. To safeguard enterprise uptime, implement client-side fallback scripts that programmatically append a local copy of the script to the DOM if the external CDN variable remains undefined.

Is pasting sensitive enterprise scripts or unreleased code inside this converter secure?

Yes, this utility is engineered with absolute zero-upload privacy. Your script content is processed locally inside your web browser using the native Web Crypto API (window.crypto.subtle.digest). No data, code strings, or cryptographic hashes are transmitted across the network, stored in databases, or forwarded to telemetry endpoints.

Related Tools