Skip to content

Instantly share code, notes, and snippets.

@cecilemuller
Last active June 14, 2021 18:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cecilemuller/8477130a4fbb427fb341f67af128ab5a to your computer and use it in GitHub Desktop.
Save cecilemuller/8477130a4fbb427fb341f67af128ab5a to your computer and use it in GitHub Desktop.
Subresource Integrity (SRI)

Subresource Integrity (SRI)

The integrity property for scripts and stylesheets:


Example

<!-- External scripts -->
<script integrity="sha512-aaaaaaaaa" crossorigin="anonymous" src="script.js"></script>

<!-- External stylesheets -->
<link integrity="sha512-aaaaaaaaa" crossorigin="anonymous" href="styles.css" rel="stylesheet">

<!-- Inline stylesheets -->
<style integrity="style-src www.example.com 'sha512-aaaaaaaaa'">
body { ... }
</style>

Create a hash

You can have multiple hashes separated by a space, but the browser uses the highest so you might as well use only one (preferably sha-512 like Github).

Node uses crypto:

import {createHash} from "crypto";

const contents = Buffer.from("CONTENTS OF THE FILE");
const integrity = "sha512-" + createHash("sha512").update(contents).digest().toString("base64");

PHP uses hash:

$contents = file_get_contents("script.js");
$integrity = 'sha512-' . base64_encode(hash("sha512", $contents, true));

Plugins to inject integrity in HTML pages:

More tools:


@cecilemuller
Copy link
Author

Also related:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment