What subresource integrity does — pinning an external file with one hash
In one sentence: the browser compares the hash of the file it received with the value in the tag, and refuses to run the file when they differ.
The order a browser checks
When fetching a script or stylesheet, a browser reads the integrity attribute first. Without a value it simply proceeds. With a value it computes a digest of the response body it fetched over CORS and compares that with the hashes in the tag.
If several hashes are listed, only the strongest algorithm is used: with sha256 and sha384 present, only sha384 is compared. When nothing matches, the resource is blocked and the console reports 'Failed to find a valid digest'.
Two parts to the syntax
An integrity value is 'algorithm- Base64 digest', and several can be joined with spaces. The algorithms are sha256, sha384 and sha512.
<script src="https://cdn.example.com/lib/app.js"
integrity="sha384-SMPwvYr9eRwR/axEGrORdN1VwWIaVuY2TTdeGWGkL6oeEalrd4V2wQI141RcZnN4"
crossorigin="anonymous"></script>
Where it applies
SRI is enforced for scripts and stylesheet links, including type="module" scripts. A preload link can carry integrity so the file is verified early, but the tag that actually uses the file needs the same value.
Inline scripts have no separate file, so integrity means nothing there; inline code belongs to CSP hashes.
A hash is a fingerprint of bytes
A hash covers bytes, not meaning. The same code with LF instead of CRLF, with or without a BOM, minified by the build, or transcoded by the server produces a completely different value.
So hash the final file the server actually sends, not the code you pasted into an editor.
What SRI does not give you
SRI checks integrity, not confidentiality. The file still travels over the network in the clear and the hash is public.
It also cannot establish trust on first visit: the hash ships with the HTML, so an attacker who can rewrite the HTML rewrites both. Protect the HTML itself with HTTPS and server-side control.
Questions
If I add integrity, is a tampering CDN harmless?
A CDN that changes the response produces a mismatch and the browser blocks it. An attacker who can also rewrite the HTML can change the hash, though, so the HTML delivery path needs its own protection.
Is there a reason to list several hashes?
Only while migrating algorithms. Browsers check the strongest one, so in practice a single sha384 token is enough.
Sources
Every example here can be pasted into the workbench as it is.
Open the workbench