3

This is what I've got so far to export a public and private key from a keypair:

let pub = await crypto.subtle.exportKey("spki", keyPair.publicKey);
let prv = await crypto.subtle.exportKey("spki", keyPair.privateKey);

This results in two individual array buffers holding my public and private key.

I would like to find out how to export the entire keypair at once into a single array buffer?

Something like this:

let pair = await crypto.subtle.exportKeyPair("spki", keyPair);

Is there a web api and a format for this?

Otherwise is there a safe way to concatenate the two array buffers (the exported public and private key) together in such a way that I can split them up again when importing? I would then need to have some mechanism to handle malformed input when importing the exported key pair.

I must do this because my interface requires me to return a single array buffer.

David Callanan
  • 5,601
  • 7
  • 63
  • 105
  • 1
    You need to export the private and public key separately and then concatenate the results, for example in base64, or use a standard format like PEM. – pedrofb Jun 17 '20 at 09:46
  • @pedrofb Thanks for your input. I manually concatenated the two buffers and added a length of the first buffer to the start so I can split it up properly when importing. I would like to use a standard format, is there a web API for exporting in the PEM format? – David Callanan Jun 17 '20 at 11:37
  • 1
    PEM is a relatively simple format. You can use a library or convert your keys yourself. See https://stackoverflow.com/a/40327542/6371459 – pedrofb Jun 17 '20 at 14:01

1 Answers1

1

I found that I can export the public key using the following code. I haven't figured out the private key just yet. Also I built this sample from the code on:
https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey#subjectpublickeyinfo_export

const exported = pub;
const exportedAsString = String.fromCharCode.apply(null, new Uint8Array(exported));
const exportedAsBase64 = window.btoa(exportedAsString);
const pemExported = '-----BEGIN PUBLIC KEY-----\n'+exportedAsBase64+'\n-----END PUBLIC KEY-----`;
console.log("Public Exported Key: ", pemExported);
jim.gray
  • 11
  • 2