vors
vors2y ago

What s the recommende way to get

What's the recommende way to get sha256 of a string nowdays? I'm trying
"use node";

import crypto from "crypto";

export function sha256(input: string): string {
const hash = crypto.createHash("sha256").update(input).digest("hex");
return hash;
}
"use node";

import crypto from "crypto";

export function sha256(input: string): string {
const hash = crypto.createHash("sha256").update(input).digest("hex");
return hash;
}
but I cannot make the this work for some reason...
2 Replies
vors
vorsOP2y ago
Error
⠙ Preparing Convex functions...
✘ [ERROR] Could not resolve "crypto"

convex/hash.ts:4:19:
4 │ import crypto from "crypto";
╵ ~~~~~~~~
⠙ Preparing Convex functions...
✘ [ERROR] Could not resolve "crypto"

convex/hash.ts:4:19:
4 │ import crypto from "crypto";
╵ ~~~~~~~~
Even after
npm i crypto
npm i crypto
ok I think solved this with adding this
"browser": {
"crypto": false
}
"browser": {
"crypto": false
}
to package.json
lee
lee2y ago
if you want to use browser crypto, which should work in queries/mutations/httpActions as well as node actions, you can do this
async function sha256(str: string) {
const buffer = new TextEncoder().encode(str);
const hash = await crypto.subtle.digest("SHA-256", buffer);
// convert to hex
return Array.from(new Uint8Array(hash)).map((b) => b.toString(16).padStart(2, "0")).join("");
}
async function sha256(str: string) {
const buffer = new TextEncoder().encode(str);
const hash = await crypto.subtle.digest("SHA-256", buffer);
// convert to hex
return Array.from(new Uint8Array(hash)).map((b) => b.toString(16).padStart(2, "0")).join("");
}
(without the "use node" or import crypto from "crypto")

Did you find this page helpful?