Subresource Integrity (SRI) | HAHWUL

Subresource Integrity (SRI) | HAHWUL

A guide to understanding and implementing Subresource Integrity (SRI) for enhanced web security.

Subresource Integrity (SRI) is a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched resource must match.

This article explains what SRI is, why it’s needed, how it works, and how to implement it.

What is SRI?

SRI is a W3C specification that allows web developers to ensure that resources hosted on third-party servers (like CDNs) have not been tampered with. By providing a cryptographic hash (integrity metadata) for a resource, the browser can verify that the fetched resource matches the expected hash before executing it. If the resource does not match, the browser will refuse to load it, preventing potential attacks.

 graph LR
    subgraph Server
        A[Generate resource hash and
embed in HTML 'integrity' attribute] end subgraph Browser B[Download resource from CDN] --> C[Calculate hash from
the downloaded resource] C --> D{Compare hashes} end A --> B D -- Match --> E[ Execute script] D -- Mismatch --> F[ Block script & throw error]

Why is SRI needed?

Websites often rely on Content Delivery Networks (CDNs) to serve common files like JavaScript libraries and CSS frameworks. This improves performance and availability. However, if a CDN is compromised, malicious actors could modify these files to inject malicious code into websites that use them. This could lead to various attacks, such as data theft or a complete site takeover.

SRI mitigates this risk by ensuring that the browser only executes code that matches the developer-provided integrity hash.

How does SRI work?

SRI works by using the integrity attribute on