[Dev] ハッシュ計算いろいろ

in #japanese4 days ago (edited)

こんにちは、@yasuです。

Node.js環境からBun.sh環境への移行を考えたとき、
必要と思う検証を行っている。

方法1:Node.js 標準 crypto

import { createHash } from "crypto";
function sha256(data: Uint8Array): Uint8Array { return new Uint8Array(createHash("sha256").update(data).digest()); }
const digest = sha256(new TextEncoder().encode(message));

方法2:dsteem の cryptoUtils.sha256

import dsteem from 'dsteem';
const digest2 = dsteem.cryptoUtils.sha256(Buffer.from(message, "utf8"));

方法3:Bun 独自 Bun.SHA256.hash

const digest3 = Bun.SHA256.hash(new TextEncoder().encode(message));

バッファ⇒Uint8Array変換

const uint8 = new Uint8Array(digest2);

■Uint8Array同士の比較

const isEqual = (a: Uint8Array, b: Uint8Array) =>  a.length === b.length && a.every((v, i) => v === b[i]);
console.log(isEqual(digest, digest2));