8

What commands could I run to manually generate (or confirm) the integrity field contained in a package-lock.json file?

Here's an example with SHA1:

"uglify-js": {
  "version": "2.8.29",
  "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.8.29.tgz",
  "integrity": "sha1-KcVzMUgFe7Th913zW3qcty5qWd0=",

And another with SHA512:

"uri-js": {
  "version": "4.2.2",
  "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz",
  "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==",

My wild guess was to run the specified hash against the tgz file and then base64 encode it, but that's not it. For example:

$ sha1sum.exe uglify-js-2.8.29.tgz
29c5733148057bb4e1f75df35b7a9cb72e6a59dd *uglify-js-2.8.29.tgz

$ sha1sum.exe uglify-js-2.8.29.tgz | cut -d " " -f1
29c5733148057bb4e1f75df35b7a9cb72e6a59dd

$ sha1sum.exe uglify-js-2.8.29.tgz | cut -d " " -f1 | base64
MjljNTczMzE0ODA1N2JiNGUxZjc1ZGYzNWI3YTljYjcyZTZhNTlkZAo=

And that obviously does not equal:

KcVzMUgFe7Th913zW3qcty5qWd0=
TTT
  • 22,611
  • 8
  • 63
  • 69

1 Answers1

11

It looks like this NPM package field is based on the Subresource Integrity calculation.

According to the linked page, the correct command for your example could be:

$ shasum -b -a 1 /path/to/uglify-js-2.8.29.tgz | awk '{ print $1 }' | xxd -r -p | base64
KcVzMUgFe7Th913zW3qcty5qWd0=

Where 1 is the cipher used (SHA1).

For SHA512, the command is a bit different (note 512 value used for -a switch):

$ shasum -b -a 512 /path/to/uri-js-4.2.2.tgz | awk '{ print $1 }' | xxd -r -p | base64
KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==
dvuckovic
  • 126
  • 2
  • 3
  • 1
    Perfect. `xxd` was the missing piece! – TTT Dec 14 '21 at 16:44
  • Thanks. I got multiple output lines, so my fix was: `shasum -b -a 512 "/path/to/uri-js-4.2.2.tgz" | awk '{ print $1 }' | xxd -r -p | base64 | awk '{ printf("%s", $0) }' | awk '{print "sha512-"$0}'` – KeKru Feb 07 '22 at 17:38
  • I was able to navigate to my local node_modules directory and run this, but unable to point to a URL. Does this work for you if you point to a remote Artifactory? – Nate May 19 '22 at 18:20
  • Commands to use on git bash/windows: `sha1sum.exe "/path/to/uri-js-4.2.2.tgz" | awk '{print $1}' | xxd -r -p | base64 -w0 | awk '{print "sha1-"$0}'` and `sha512sum.exe "/path/to/uri-js-4.2.2.tgz" | awk '{print $1}' | xxd -r -p | base64 -w0 | awk '{print "sha512-"$0}'` – Jidehem Jan 11 '23 at 16:01