Skip to main content

How to Generate a Subresource Integrity (SRI) Hash for a Script in the Terminal

· 9 min read
Jagdish Kumawat
Founder @ Dewiride

A <script> tag that loads code from another site, such as a CDN, runs whatever that site sends. An integrity attribute with the file's hash makes the browser check the file first, and refuse to run it if even one character changed. You make the hash with one command in the terminal.

Syntax​

The attribute, on the script tag:

Syntax
<script src="<file>"
integrity="sha384-<hash>"
crossorigin="anonymous"></script>

The command that makes its value, on macOS and Linux:

Syntax (macOS / Linux)
echo "sha384-$(openssl dgst -sha384 -binary <file> | openssl base64 -A)"

And in PowerShell 7.6:

Syntax (PowerShell)
$bytes = Get-Content -Path <file> -AsByteStream -Raw
"sha384-" + [Convert]::ToBase64String([System.Security.Cryptography.SHA384]::HashData($bytes))
PartWhat it does
integrity="sha384-<hash>"The hash the file must have: the algorithm, a dash, then the hash in base64
crossorigin="anonymous"Fetches the file with CORS, which the browser needs before it can check a file from another site
openssl dgst -sha384 -binary <file>Makes the file's SHA-384 hash as raw bytes
openssl base64 -ATurns those bytes into base64, on one line
echo "sha384-$(...)"Puts the sha384- prefix in front, so the output is the whole attribute value
SHA384.HashData and ToBase64StringThe same two steps in PowerShell, with .NET

MDN's Subresource Integrity guide describes the feature: 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. The allowed prefixes are sha256, sha384 and sha512. sha384 is the one MDN's examples use.

The Example​

A page, index.html, says The script hasn't run. until its script, greeting.js, replaces the text with Hello from greeting.js! The guide makes the script's hash, puts it on the script tag, changes the script, and watches the browser refuse it until the hash is made again.

Prerequisites​

  • macOS or Linux: OpenSSL. Check with openssl version. This guide used OpenSSL 4.1.0. The LibreSSL openssl that comes with macOS gave the same hash.
  • Windows: PowerShell 7.6, the current long-term support release. Windows PowerShell 5.1 has neither Get-Content -AsByteStream nor SHA384.HashData.
  • Python 3, for a small local web server. Check with python3 --version, or py --version on Windows. This guide used Python 3.15.2.

Step 1: Write the Script​

Create a folder for the example, and in it a file named greeting.js:

greeting.js
document.getElementById("greeting").textContent = "Hello from greeting.js!";

It finds the element with the ID greeting and replaces its text.

Step 2: Make Its Hash​

In the same folder:

Terminal
echo "sha384-$(openssl dgst -sha384 -binary greeting.js | openssl base64 -A)"
Output
sha384-uh0CzMFTgfAeH+YhrLE0flpqW+lsfjY0F9neG2jdFQo75Bb8wepYwQ+7EF8x8JjY

A zsh terminal running echo "sha384-$(openssl dgst -sha384 -binary greeting.js | openssl base64 -A)", which prints sha384-uh0CzMFTgfAeH+YhrLE0flpqW+lsfjY0F9neG2jdFQo75Bb8wepYwQ+7EF8x8JjY.

-binary hands the raw hash to openssl base64. Without it, openssl dgst prints the hash as hexadecimal text, and base64 of that text is a different, wrong value.

Both give the same value, because the hash depends only on the file's bytes. Your value will differ if your file differs in any way, even by one space or a different line ending.

Step 3: Put the Hash on the Script Tag​

Create index.html next to greeting.js, with the value from Step 2:

index.html in a macOS-style code window: a paragraph with the ID greeting that says The script hasn't run., and a script tag for greeting.js with integrity sha384-uh0CzMFTgfAeH+YhrLE0flpqW+lsfjY0F9neG2jdFQo75Bb8wepYwQ+7EF8x8JjY and crossorigin anonymous.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SRI demo</title>
</head>
<body>
<p id="greeting">The script hasn't run.</p>
<script src="greeting.js"
integrity="sha384-uh0CzMFTgfAeH+YhrLE0flpqW+lsfjY0F9neG2jdFQo75Bb8wepYwQ+7EF8x8JjY"
crossorigin="anonymous"></script>
</body>
</html>

Step 4: Open the Page​

The page has to come from a web server: opened straight from the disk, the browser blocks the script for another reason, as Fixed: Access to script at 'file:///…' from origin 'null' has been blocked by CORS policy shows. Python has a small one built in. In the folder:

Terminal
python3 -m http.server 8081
Output
Serving HTTP on :: port 8081 (http://[::]:8081/) ...

It serves the folder's files at http://localhost:8081/ until you press Ctrl+C. Open that address in a browser:

A browser page showing Hello from greeting.js!

The browser made its own hash of greeting.js, found it equal to the one on the tag, and ran the script.

Step 5: Change the Script​

Now change the text in greeting.js, as an update to the file would:

greeting.js
document.getElementById("greeting").textContent = "Hello from the new greeting.js!";

Reload the page. The text stays as it was, because the browser didn't run the script:

The same browser page, still showing The script hasn't run.

The browser's console, which F12 opens in Chrome and Edge, says why:

Console
Failed to find a valid digest in the 'integrity' attribute for resource 'http://localhost:8081/greeting.js' with computed SHA-384 integrity 'IVgd0lDQl4XfieCfj3m+tlhOPZteADgAx/Sn3z5gsb8AZaPQR+Gf/lI6vqmG51R0'. The resource has been blocked.

This is SRI doing its job. MDN describes the check: if the actual value matches any of the specified values, then the browser will load the resource, otherwise it will refuse to load the resource, and return a network error. If someone had changed a file on a CDN, your page would refuse it the same way.

Step 6: Make a New Hash for the New File​

When the change is one you trust, make the hash again, exactly as in Step 2:

Output
sha384-IVgd0lDQl4XfieCfj3m+tlhOPZteADgAx/Sn3z5gsb8AZaPQR+Gf/lI6vqmG51R0

Replace the old value in index.html's integrity attribute with it, and reload:

The browser page now showing Hello from the new greeting.js!

The console's message showed the same hash. Make it yourself anyway, from a file you trust: copying it from the error would approve whatever the server sent.

Stop the web server with Ctrl+C when you're done.

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out -binaryThe hash is of the hexadecimal text, and the browser blocks the scriptKeep -binary before the file name
Leaving out the sha384- prefixThe console says Error parsing 'integrity' attribute, and the browser runs the script without checking itStart the value with sha384-
Hashing a copy that differs from what the site servesThe browser blocks the scriptHash the exact file at the exact URL, such as a CDN file downloaded with curl -o
Leaving out crossorigin="anonymous" on a script from another siteBlocked: the resource requires the request to be CORS enabled to check the integrity, and it is notKeep crossorigin="anonymous"
Using a CDN address that changes, such as a latest versionThe file changes and the page breaksLoad an exact version, and hash that file

Troubleshooting​

SymptomLikely causeFix
Failed to find a valid digest in the 'integrity' attributeThe file and the hash don't matchMake the hash again from the file the page loads
No 'Access-Control-Allow-Origin' header is present on the requested resourceThe other site doesn't allow CORS for that fileUse a CDN that does, or host the file yourself
Access to script at 'file:///…' from origin 'null' has been blocked by CORS policyThe page was opened from the diskServe the folder, as in Step 4
openssl: command not foundOpenSSL isn't installed or isn't on the PATHInstall it, or use the PowerShell tab

FAQ​

Does SRI work for CSS files too?​

Yes. The same integrity and crossorigin attributes go on a <link rel="stylesheet"> tag, with the stylesheet's hash.

Why sha384 and not sha256?​

Both are allowed, along with sha512, and any of them catches a changed file. sha384 is the one MDN's examples use.

Do I need SRI for my own scripts?​

It matters most for files you don't host yourself, because those can change without you knowing. For your own files, you control what's on the server.

Conclusion​

An integrity attribute holds a file's hash, and the browser runs the file only if its own hash matches. Make the value with openssl dgst -sha384 -binary and openssl base64 -A on macOS and Linux, or SHA384.HashData in PowerShell 7.6, and put sha384- in front. Add crossorigin="anonymous", and make a new hash whenever you move to a new version of the file.

Additional Resources​