summaryrefslogtreecommitdiffhomepage
path: root/packages/server/src/helpers/convertCOSEtoPKCS.ts
blob: 65f795d3a8c883a976d4a89fc2862590c617f9ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { isoCBOR, isoUint8Array } from './iso/index.ts';
import { COSEKEYS, COSEPublicKeyEC2 } from './cose.ts';

/**
 * Takes COSE-encoded public key and converts it to PKCS key
 */
export function convertCOSEtoPKCS(cosePublicKey: Uint8Array): Uint8Array {
  // This is a little sloppy, I'm using COSEPublicKeyEC2 since it could have both x and y, but when
  // there's no y it means it's probably better typed as COSEPublicKeyOKP. I'll leave this for now
  // and revisit it later if it ever becomes an actual problem.
  const struct = isoCBOR.decodeFirst<COSEPublicKeyEC2>(cosePublicKey);

  const tag = Uint8Array.from([0x04]);
  const x = struct.get(COSEKEYS.x);
  const y = struct.get(COSEKEYS.y);

  if (!x) {
    throw new Error('COSE public key was missing x');
  }

  if (y) {
    return isoUint8Array.concat([tag, x, y]);
  }

  return isoUint8Array.concat([tag, x]);
}