Skip to content

A brower, node, and bun-compatible synchronous sha256 implementation using TypedArray

License

Notifications You must be signed in to change notification settings

therootcompany/sha256.js

Repository files navigation

A brower, node, and bun-compatible synchronous sha256 implementation using typed arrays

For Browsers

<script src="https://unpkg.com/@root/sha256@1/sha256.js"></script>
let Sha256 = window.Sha56;

let msg = "Hello, World!";
let encoder = new TextEncoder();
let bytes = encoder.encode(msg);

let hashBytes = Sha256.sha256(bytes);
console.log(hashBytes);
let hex = bytesToHex(hashBytes);
console.log(hex);

function bytesToHex(bytes) {
  let hexes = [];

  for (let b of bytes) {
    let h = b.toString(16);
    h = h.padStart(2, "0");
    hexes.push(b);
  }

  let hex = hexes.join("");
  return hex;
}

For Node, Bun, and Bundlers

npm install --save @root/sha256@1
let Sha256 = require("@root/sha256");

let msg = "Hello, World!";
let encoder = new TextEncoder();
let bytes = encoder.encode(msg);

let hashBytes = Sha256.sha256(bytes);
console.log(hashBytes);

let buf = Buffer.from(hashBytes);
let hex = buf.toString("hex");
console.log(hex);

Why?

  • WebCrypto's SHA-256 is asynchronous, which means:
    • it's very slow (context switches on each call)
    • it colors all the functions (sha256 is cpu-bound and typically sync)
  • Other popular implementations have bespoke psuedo-buffers (not TypedArrays)
  • Refactoring other implementations is tedious and error-prone

References

Since hundreds (if not thousands) of correct implementations exist, this was primarily generated via prompt-engineering rather than ported by hand (which is error-prone due to the differences in endianness, int width and sign, etc). However, the code has been manually compared to other implementations for correctness, and the results have been verified through over a thousand tests.

To compare to other known-working implementations, consider:

License

Copyright 2024 AJ ONeal (MPL-2.0 License)

About

A brower, node, and bun-compatible synchronous sha256 implementation using TypedArray

Resources

License

Stars

Watchers

Forks

Packages

No packages published