How Subresource Integrity Verifies External JavaScript

Subresource Integrity (SRI) is a web security standard that enables browsers to verify that external files, such as JavaScript libraries delivered via Content Delivery Networks (CDNs), are delivered without unexpected manipulation. By comparing a cryptographic hash defined in your HTML with the hash of the fetched file, SRI ensures that your web application only executes trusted, unmodified code, mitigating the risks of supply-chain attacks and compromised third-party servers.

The Core Mechanism of Subresource Integrity

SRI relies on cryptographic hashing algorithms (typically SHA-256, SHA-384, or SHA-512) to validate the authenticity and integrity of fetched files. The verification process follows a strict step-by-step workflow between your web page, the external host, and the client’s browser:

1. Generating the Cryptographic Hash

Before deploying the code, the developer computes a cryptographic hash of the exact JavaScript file to be hosted externally. This hash is encoded in base64 format and prefixed with the algorithm used (for example, sha384-).

2. Declaring the Integrity Attribute

The generated hash string is placed inside the integrity attribute of the <script> tag in the HTML document. Alongside it, the crossorigin="anonymous" (or use-credentials) attribute is required to enforce Cross-Origin Resource Sharing (CORS) validation.

<script 
  src="https://cdn.example.com/library.js" 
  integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC" 
  crossorigin="anonymous">
</script>

3. Fetching and Comparing on the Client Side

When a user loads the page: * Download: The browser fetches the external JavaScript file from the specified URL. * Calculation: Before executing the script, the browser calculates its own cryptographic hash of the downloaded content using the algorithm specified in the integrity attribute. * Validation: The browser compares its generated hash to the hash provided in the HTML.

4. Execution or Blocking

Why SRI Verification is Critical