Skip to content

Instantly share code, notes, and snippets.

@varjmes
Created March 30, 2019 09:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save varjmes/b1a88c787c14cfe1177def7114dffba3 to your computer and use it in GitHub Desktop.
Save varjmes/b1a88c787c14cfe1177def7114dffba3 to your computer and use it in GitHub Desktop.
Calculating SHA-1's of various strings to replicate how git calculates object filenames
// Calculating and printing the SHA-1 hash of strings
const crypto = require('crypto')
const zlib = require('zlib')
function hashIt(string) {
return crypto
.createHash('sha1')
.update(string, 'utf-8')
.digest('hex')
}
const string = 'hello\n'
const stringHexDigest = hashIt(string)
console.log(`raw: ${stringHexDigest}`)
const blob = `blob ${Buffer.byteLength(string)}\0${string}`
const blobHexDigest = hashIt(blob)
console.log(`blob: ${blobHexDigest}`)
const zipped = zlib.deflateSync(blob)
const zippedHexDigest = hashIt(zipped)
console.log(`zipped: ${zippedHexDigest}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment