aboutsummaryrefslogtreecommitdiff
path: root/sri-hash
blob: bb9f5d9fd35ddd64bc3c9da416768530058582ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/bin/sh
#
# SRI Hash Generator
#
# A safer alternative than using external services such as
# https://www.srihash.org
#

# Parameters
BASENAME="`basename $0`"
URI="$1"
TYPE="${2:-sha512}"

# Check
if [ -z "$URI" ]; then
  echo "usage: $BASENAME <file-or-url>"
  exit 1
fi

# Get file
if echo "$URI" | grep -q '^http'; then
  echo "downloading $URI and generating hash..."
  HASH="`curl $URI | openssl dgst -$TYPE -binary | openssl base64 -A`"
  echo ""
else
  if [ -e "$URI" ]; then
    # See https://www.srihash.org/
    HASH="`openssl dgst -$TYPE -binary $URI | openssl base64 -A`"
  else
    echo "file not found: $URI"
    exit 1
  fi
fi

# Generate
if echo $URL | grep -q '.js$'; then
  cat <<EOF
<script
  src="$URI"
  integrity="$TYPE-$HASH"
  crossorigin="anonymous"
  referrerpolicy="no-referrer"
></script>
EOF
else
  cat <<EOF
<link
  href="$URI"
  rel="stylesheet"
  integrity="$TYPE-$HASH"
  crossorigin="anonymous"
  referrerpolicy="no-referrer"
></script>
EOF
fi