A step-by-step guide on creating a private/public key pair and utilizing the private key to sign data with the Webcrypto API

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.

Answer №1

To ensure proper functionality, it is important to provide a specific name and hash for the signature algorithm. When dealing with an ECDSA signature, make sure to include an EcdsaParams object when using the sign() function:

const sign = async function(privateKey: CryptoKey, buffer: BufferSource) {
    return crypto.subtle.sign({
      name: 'ECDSA',
      hash: 'SHA-512'
    }, privateKey, buffer);
};

Playground link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having issues showcasing the array of objects stored in $scope in AngularJs

I'm encountering an issue where I can't seem to display the values of my scope variables. Even though I'm new to Angular, I've successfully done this many times before. Here are the key parts of my index.html file. The div-ui element is ...

Is it possible to convert an object and/or a nested array with objects into a JSON string without relying on JSON.stringify?

Struggling to generate a correct JSON string from an object without relying on JSON.stringify(). Presenting my current implementation below - var my_json_encode = function(input) { if(typeof(input) === "string"){ return '"'+input+&apo ...

Guide on Triggering a Custom Popup Message upon a Server Action in Next.js

Hey there, I'm currently facing some difficulties in finding the proper way to trigger a toast notification after successfully mutating data using server actions in Nextjs 13. The toast component I'm working with is specifically designed for clie ...

Reducing size and Assembling JavaScript and CSS

I find myself in a bit of a dilemma when it comes to using just one JS file and one CSS file for a website. Let me elaborate: As someone who mainly works with CMS platforms like Joomla, I often run into issues during page speed tests where experts recomme ...

Guidelines for modifying a useState function containing an array with objects that dynamically update based on changes to input values in a React.js application

const [fvalues,setFvalues]=useState(data.map((ele,id)=>{ return( {mobile:'',age:'',emailId:'',destinationAddress:'',destinationPin:''} ); })); I am trying to update these objects whenever th ...

Toggling the form's value to true upon displaying the popup

I have developed an HTML page that handles the creation of new users on my website. Once a user is successfully created, I want to display a pop-up message confirming their creation. Although everything works fine, I had to add the attribute "onsubmit= re ...

Circular Plane with THREE JS

When working with THREE JS, I've noticed that it tends to have a very angular and straight-edged look. Although I haven't been using it for long, I am struggling to figure out how to give the world a more curved appearance. My goal is to take a 2 ...

What is the best way to display an HTML page in the bottom right corner instead of within a div?

I am trying to display the content of an HTML page in the bottom right corner of another page using my JavaScript script. However, I do not want to insert a div into the page and then load the content inside it. Instead, I am looking for an alternative way ...

Is it acceptable to debut a full-screen iframe widget compared to an embedded one?

My current project involves integrating a custom widget into users' websites for my application. I am considering using an iframe as it seems to be the most efficient option for several reasons: Utilizing the custom framework of the application will ...

Remove a error notification rather than appending it using javascript

Within this HTML form, I aim to notify the user that they must input a level into the text box. If the user clicks the button again, I want to erase the error message and display it once more. Moreover, I intend to include additional error messages; howeve ...

Arranging JSON objects in an array based on date, with the ability to include a 13th month in the date format

I have a function that successfully sorts an array of JSON objects by date, but I need it to also accommodate the 13th month (salary). module = {}; module.exports = [ { "date": "01-2012" }, { "date": "12-2011" }, { ...

IIS Alert: Missing Images, CSS, and Scripts!

When I tried to publish my website using IIS, I encountered the error message Cannot read configuration file due to insufficient permissions. After attempting to add permissions for IIS_USRS and realizing that this user does not exist on my computer runnin ...

What is the best way to start a node server while utilizing a testing framework?

Just to provide a bit of context, I'm currently implementing BDD using Cucumber.js in an express/node application. It has worked smoothly for me in Rails, so I decided to stick with the same framework. However, I am facing an issue where I have to man ...

Submitting a form that was loaded using jQuery cannot be done with jQuery

After successfully using jQuery to load a form from the sidebar to the main page, I encountered an issue with submitting the form using jQuery as well. Although I have previously used the same jQuery code to submit forms that were not loaded with jQuery, t ...

How can I simultaneously submit both the file and form data from two separate forms on a single page using PHP?

My webpage features a form with a series of questions, each followed by an option to upload files if available. I made sure not to nest forms within each other, instead using a method where the upload form pops up separately. However, I encountered an issu ...

Uncovering the deepest levels of nested arrays and objects in JavaScript without any fancy libraries - a step-by-step guide!

I have been struggling to find a solution to a seemingly simple problem. Despite searching through various sites and resources, I have not been able to figure out how to iterate over the innermost levels of a doubly nested data structure. I have tried usin ...

Triggering a JavaScript function when the mouse moves off an element

Recently, I created the following code snippet for marquee effect. The main functionality it is missing is triggering a function on mouse-over. <marquee class="smooth_m" behavior="scroll" direction="left" scrollamount="3"> <span style="float:le ...

What is the best approach for managing interactive infographics using JavaScript?

I've been tasked with a project that involves creating a dynamic data visualization using JavaScript. You can check out the final product here. The goal is to take information from a provided PDF and find a way to display it dynamically on an image. ...

Guide on resetting a value in ajax search to enable pagination of results

I've run into an issue with a "load more button". Each time I perform a new search, I want to display the second page of results and subsequent pages. However, the value I'm using to determine the current page keeps increasing continuously. I nee ...

How to Properly Import a Component into the Root Component in React and Ensure it Renders Correctly

I've been attempting to bring in a Navbar component created with the Radix library into the root component App.js of my React application. I've experimented with both named and default exports to render the component, but neither option seems to ...