Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: example generating keypairs with WebCrypto & node:crypto #10

Open
coolaj86 opened this issue Oct 6, 2024 · 0 comments
Open

doc: example generating keypairs with WebCrypto & node:crypto #10

coolaj86 opened this issue Oct 6, 2024 · 0 comments

Comments

@coolaj86
Copy link
Contributor

coolaj86 commented Oct 6, 2024

'use strict';

let Fs = require('node:fs/promises');

async function generateKeyPair(algo) {
  let keyPair = await crypto.subtle.generateKey(algo, true, ['sign', 'verify']);

  let name = algo.namedCurve || algo.name;

  let privateKeyAb = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey);
  let privateKeyDER = new Uint8Array(privateKeyAb);
  let privateKeyPath = `./key.${name}.der`.toLowerCase();
  await Fs.writeFile(privateKeyPath, privateKeyDER);

  let publicKeyAb = await crypto.subtle.exportKey('spki', keyPair.publicKey);
  let publicKeyDER = new Uint8Array(publicKeyAb);
  let publicKeyPath = `./pub.${name}.der`.toLowerCase();
  await Fs.writeFile(publicKeyPath, publicKeyDER);

  console.info(`Key pair generated and saved as ${privateKeyPath} and ${publicKeyPath}`);
}

let Crypto = require('node:crypto');

async function generateSecp256k1KeyPair() {
  return new Promise(function (resolve, reject) {
    Crypto.generateKeyPair(
      'ec',
      {
        namedCurve: 'secp256k1',
        publicKeyEncoding: {
          type: 'spki',
          format: 'der',
        },
        privateKeyEncoding: {
          type: 'pkcs8',
          format: 'der',
        },
      },
      async function (err, publicKey, privateKey) {
        if (err) {
          return reject(err);
        }

        await Fs.writeFile('./key.secp256k1.der', privateKey);
        await Fs.writeFile('./pub.secp256k1.der', publicKey);

        console.info(
          'secp256k1 key pair generated and saved as ./key.secp256k1.der and ./pub.secp256k1.der',
        );
      },
    );
  });
}

async function main() {
  await generateKeyPair({ name: 'Ed25519' });
  await generateKeyPair({ name: 'ECDSA', namedCurve: 'P-256' });
  // this should be possible with WebCrypto as well, but I don't know the name to use
  //await generateKeyPair({ name: 'ECDSA', namedCurve: 'secp256k1' });
  // it does work with node:crypto
  await generateSecp256k1KeyPair();
}

main().catch(function (err) {
  console.error(err.stack);
  process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant