Generate Key Pair

Overview

We are using elliptic curve cryptography (ECC) for our encryption. The key pair should be generated using P-256 curve. Ensure the generated key pair is in PEM format.

The public key should be encoded in SPKI format, and the private key should be encoded in PKCS#8 format.

Public Key Format

  1. PEM format

  2. SPKI encoding

Private Key Format

  1. PEM format

  2. PKCS#8 encoding

Example Implementation

Here's the example of generating key pair in Typescript.

import crypto from "crypto";

interface PublicKeyJWKS {
  x: string;
  y: string;
  kid: string;
}

function generateKeyPair() {
  const keypair = crypto.generateKeyPairSync("ec", {
    namedCurve: "prime256v1",
    publicKeyEncoding: { type: "spki", format: "pem" },
    privateKeyEncoding: { type: "pkcs8", format: "pem" },
  });
  const lines: string[] = keypair.publicKey.trim().split("\n");

  const x = lines[1];
  const y = lines[2];

  const kid = "kid-for-your-key-pair";

  const publicKeyJWKS: PublicKeyJWKS = {
    x,
    y,
    kid,
  };

  const privateKey: string = keypair.privateKey;
  console.log({ publicKeyJWKS, privateKey });
  ...
}

Output Example

After this section you should have a key pair consisting of :

  1. publicKeyJWKS

  2. privateKey

Ideally, the issuer & verifier should have different key pairs.

Make sure you have both them before proceeding to the next section.

Here's the example for publicKeyJWKS and privateKey.

{
  publicKeyJWKS: {
    x: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELOmrNI4A9ML4iGJXpYlaZiYGVCxB',
    y: 'k+evjhOZEbCLj17o/ZdfEv7dUZIRKRoZ1bud5Gq8OCItDlXkTyMrtWrhdA==',
    kid: 'q6ZFSOJcTiZWJWkvUshpFw5v20xstZN/T4lt4zpKsUg='
  },
  privateKey: '-----BEGIN PRIVATE KEY-----\n' +
    'MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgrSuv5exgvZGmELOL\n' +
    'RkT9fhhRxKW3SQASrTVbENIN5cKhRANCAAQs6as0jgD0wviIYleliVpmJgZULEGT\n' +
    '56+OE5kRsIuPXuj9l18S/t1RkhEpGhnVu53karw4Ii0OVeRPIyu1auF0\n' +
    '-----END PRIVATE KEY-----\n'
}

Last updated