I am looking to utilize the Webcrypto API to sign data, retrieve the signature and the public key while ensuring the private key remains secure. Here are a couple of helpful links:
After consulting the documentation, I have begun with the following code snippet:
const generateKeyPair = async function() {
return crypto.subtle.generateKey(
{
name: "ECDSA",
namedCurve: "P-384",
},
true,
["sign", "verify"]
);
}
const sign = async function(privateKey: CryptoKey, buffer: BufferSource) {
return crypto.subtle.sign(privateKey.algorithm, privateKey, buffer);
}
Upon testing, it seems that the generateKeyPair
function is functioning correctly. However, when attempting to use the sign
function in the test scenario as shown below:
import { describe, it, expect } from "vitest";
import { generateKeyPair, sign } from "../../src";
describe("sign", () => {
it('returns a signature.', async () => {
const { privateKey } = await generateKeyPair();
const data = { foo: 'bar' };
const stringifiedData = JSON.stringify(data);
const buffer = Buffer.from(stringifiedData);
await expect(sign(privateKey, buffer)).resolves.toBeTruthy() // expect signature here
});
});
An error occurs during testing, displaying the message:
Error: promise rejected "TypeError [ERR_MISSING_OPTION]: algorithm.hash is required" instead of resolving
It appears that the privateKey.algorithm
is missing the necessary hash
field internally. Is there an issue with the algorithm being used? I attempted to include
"hash": "SHA-512"
within the options of the generateKeyPair
method to address this.
In essence, my goal is to generate a key pair, with the private key for signing purposes and the public key for verification. Any suggestions or insights would be appreciated.