Skip to content

Instantly share code, notes, and snippets.

@modrobert
Created February 28, 2024 05:48
Show Gist options
  • Save modrobert/7484196f2c6dac606df867533399956c to your computer and use it in GitHub Desktop.
Save modrobert/7484196f2c6dac606df867533399956c to your computer and use it in GitHub Desktop.
nodejs sha256 implementation
#!/usr/bin/env node
// sha256.js by modrobert in 2024
"use strict";
const fs = require("fs");
const crypto = require("crypto");
if (process.argv.length === 2 || process.argv[2] === "-h") {
console.error("usage; sha256.js <file> || -");
process.exit(1);
}
let fileName = process.argv[2];
const sha256 = async (fileName) => {
let input;
if (fileName === "-") {
input = process.stdin;
} else {
input = fs.createReadStream(fileName);
}
let hasher = crypto.createHash("sha256");
for await (let chunk of input) {
hasher.update(chunk);
}
return hasher.digest("hex");
};
sha256(fileName).then(hash => { console.log(hash); });
@modrobert
Copy link
Author

 $ time sha256.js ubuntu-22.04.3-desktop-amd64.iso 
a435f6f393dda581172490eda9f683c32e495158a780b5a1de422ee77d98e909

real	0m3.257s
user	0m2.938s
sys	0m1.428s
$ time /usr/bin/sha256sum ubuntu-22.04.3-desktop-amd64.iso 
a435f6f393dda581172490eda9f683c32e495158a780b5a1de422ee77d98e909  ubuntu-22.04.3-desktop-amd64.iso

real	0m14.767s
user	0m14.253s
sys	0m0.512s

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