sign message in javascript

To sign a message in JavaScript, you can use the crypto object in the web crypto API. Here's an example code snippet that demonstrates how to sign a message using RSA with the SHA-256 hash algorithm:

index.tsx
// Generate a new RSA key pair
crypto.subtle.generateKey(
   {
       name: "RSASSA-PKCS1-v1_5",
       modulusLength: 2048,
       publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
       hash: "SHA-256",
   },
   true,
   ["sign", "verify"]
)
.then((keyPair) => {
    // Convert the message and private key to ArrayBuffer
    const message = new TextEncoder().encode("Hello, world!");
    const privateKey = keyPair.privateKey;

    // Sign the message using the private key
    crypto.subtle.sign(
       {
           name: "RSASSA-PKCS1-v1_5",
       },
       privateKey,
       message
    )
    .then((signature) => {
        // `signature` is an ArrayBuffer containing the signature
        console.log(new Uint8Array(signature));
    })
    .catch((error) => {
        console.error("Error signing the message:", error);
    });
})
.catch((error) => {
    console.error("Error generating key pair:", error);
});
923 chars
36 lines

Make sure to run this code in a secure environment, and handle the private key with care. Also, note that this example uses the RSA algorithm with a modulus length of 2048 bits and the SHA-256 hash algorithm. You can modify these parameters as needed.

Keep in mind that cryptographic operations such as signing messages require careful consideration of various security aspects, including key management, algorithm selection, and secure communication channels.

gistlibby LogSnag