SRI hashes for CDN js and css files

Subresource Integrity is a nifty idea to use SRI hashes to verify external resources your web app depends on haven’t been compromised.

Using content delivery networks (CDNs) for common web resources (javascript and css) makes pages load faster since chances are those things have been loaded by other sites and are cached by the browser. It also means bandwidth gets used better generally which is a good thing.

But it does mean you’re trusting the CDN. With SRI hashes you don’t need to trust it as much - though IE users will, but then if you’re using Microsoft products you don’t care about security so not that big a deal.

You can use a website to calculate those SRI hashes for you. Alternatively you can just use this script:


# sri-hash-gen - calculate sri hashes for urls.
if [[ -z "$1" || "$1" == -h || "$1" == --help ]]; then
  echo "USAGE: $0 url1 ... urlN"

for url in "$@"; do
  h=sha384-$(curl -s "$url" \
        | openssl dgst -sha384 -binary \
        | openssl enc -base64 -A)
  case "$url" in
      echo "<script src=\"$url\" integrity=\"$h\" crossorigin=\"anonymous\"></script>"
      echo "<link rel=\"stylesheet\" href=\"$url\" integrity=\"$h\" crossorigin=\"anonymous\">"
      echo "$h"