Limited Time Free!  Experience website acceleration and advanced security protection!
Get Started Now 

RSA Digital Signature

The Rivest-Shamir-Adleman (RSA) algorithm is a widely used public key cryptosystem for secure data transmission. It is mainly used for encryption, decryption, and digital signatures. RSA provides a high level of security due to its use of a pair of keys, one public and one private. The public key is used for encryption or signature verification, while the private key is used for decryption or signing.

In this example, an Edge Function is used the Web Crypto API to implement RSA signing and signature verification.

Code

async function signMessage(message, privateKey) {
  const encoder = new TextEncoder();
  const data = encoder.encode(message);
  return await crypto.subtle.sign(
    {
      name: 'RSA-PSS',
      saltLength: 32,
    },
    privateKey,
    data,
  );
}

async function verifyMessage(message, signature, publicKey) {
  const encoder = new TextEncoder();
  const data = encoder.encode(message);
  return await crypto.subtle.verify(
    {
      name: 'RSA-PSS',
      saltLength: 32,
    },
    publicKey,
    signature,
    data,
  );
}

async function generateKeyPair() {
  return await crypto.subtle.generateKey(
    {
      name: 'RSA-PSS',
      modulusLength: 2048,
      publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
      hash: 'SHA-256',
    },
    true,
    ['sign', 'verify'],
  );
}

async function handleRequest() {
  const text = 'An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.';

  const keyPair = await generateKeyPair();
  const signed = await signMessage(text, keyPair.privateKey);
  const result = await verifyMessage(text, signed, keyPair.publicKey);

  return new Response(JSON.stringify({ result }));
}

addEventListener('fetch', (event) => {
  event.respondWith(handleRequest());
});


Preview

Xnip2024-07-02_18-21-56.png

References