60 lines
1.4 KiB
TypeScript
60 lines
1.4 KiB
TypeScript
import * as mod from "node:crypto";
|
|
import { atob } from "node:buffer";
|
|
|
|
/// Copy pasted from Mozilla
|
|
function str2ab(str: string) {
|
|
const buf = new ArrayBuffer(str.length);
|
|
const bufView = new Uint8Array(buf);
|
|
for (let i = 0, strLen = str.length; i < strLen; i++) {
|
|
bufView[i] = str.charCodeAt(i);
|
|
}
|
|
return buf;
|
|
}
|
|
|
|
export async function signatureVerifierV1(
|
|
msgData: ArrayBuffer,
|
|
signature: ArrayBuffer,
|
|
Ku: mod.webcrypto.CryptoKey,
|
|
) {
|
|
// UGLY: Assuming ECDSA P-256
|
|
|
|
return await mod.subtle.verify(
|
|
{
|
|
name: "ECDSA",
|
|
hash: "SHA-256",
|
|
},
|
|
Ku,
|
|
signature,
|
|
msgData,
|
|
);
|
|
}
|
|
|
|
export async function pem2_P256key(filePath: string) {
|
|
const publicKeyBytes = await Deno.readFile(filePath);
|
|
const pemKey = new TextDecoder().decode(publicKeyBytes);
|
|
|
|
// fetch the part of the PEM string between header and footer
|
|
const pemHeader = "-----BEGIN PUBLIC KEY-----";
|
|
const pemFooter = "-----END PUBLIC KEY-----";
|
|
const pemContents = pemKey.substring(
|
|
pemHeader.length,
|
|
pemKey.length - pemFooter.length - 1,
|
|
);
|
|
// base64 decode the string to get the binary data
|
|
// convert from a binary string to an ArrayBuffer
|
|
const a = atob(pemContents);
|
|
const binaryDer = str2ab(a);
|
|
|
|
// UGLY: Assuming P-256
|
|
return mod.subtle.importKey(
|
|
"spki",
|
|
binaryDer,
|
|
{
|
|
name: "ECDSA",
|
|
namedCurve: "P-256",
|
|
},
|
|
true,
|
|
["verify"],
|
|
);
|
|
}
|