diff --git a/client/space_lua/stdlib/crypto.ts b/client/space_lua/stdlib/crypto.ts new file mode 100644 index 00000000..3b139951 --- /dev/null +++ b/client/space_lua/stdlib/crypto.ts @@ -0,0 +1,10 @@ +import { LuaBuiltinFunction, LuaTable } from "../runtime.ts"; +import { hashSHA256 } from "../../../plug-api/lib/crypto.ts"; + +export const cryptoApi = new LuaTable({ + sha256: new LuaBuiltinFunction( + (_sf, s: string | Uint8Array): Promise => { + return hashSHA256(s); + }, + ), +}); diff --git a/client/space_lua/stdlib/crypto_test.lua b/client/space_lua/stdlib/crypto_test.lua new file mode 100644 index 00000000..0e0e8310 --- /dev/null +++ b/client/space_lua/stdlib/crypto_test.lua @@ -0,0 +1,10 @@ +local function assertEqual(a, b) + if a ~= b then + error("Assertion failed: " .. a .. " is not equal to " .. b) + end +end + + +local s = crypto.sha256(encoding.utf8Encode("test")) +local s2 = crypto.sha256("test") +assertEqual(s, s2) diff --git a/plug-api/lib/crypto.ts b/plug-api/lib/crypto.ts index b78c7120..8282fc83 100644 --- a/plug-api/lib/crypto.ts +++ b/plug-api/lib/crypto.ts @@ -37,13 +37,20 @@ export function base64DecodeDataUrl(dataUrl: string): Uint8Array { * Note: this will only work over HTTPS * @param message */ -export async function hashSHA256(message: string): Promise { +export async function hashSHA256( + message: string | Uint8Array, +): Promise { // Transform the string into an ArrayBuffer const encoder = new TextEncoder(); - const data = encoder.encode(message); + const data: Uint8Array = typeof message === "string" + ? encoder.encode(message) + : message; // Generate the hash - const hashBuffer = await globalThis.crypto.subtle.digest("SHA-256", data); + const hashBuffer = await globalThis.crypto.subtle.digest( + "SHA-256", + data as BufferSource, + ); // Transform the hash into a hex string return Array.from(new Uint8Array(hashBuffer)).map((b) =>