FIDO2 U2F X509 in NodeJS

For Decentralized identity implementations in Distributed Ledgers and Blockchain development, the new Cryptography primitives are:

When user registers a FIDO2 device for authentication, your server will receive an attestation statement object containing x509 and signature objects in u2fStmtFormat as below:

u2fStmtFormat = {
  x5c: [ attestnCert: bytes ],
  sig: bytes
where, as per the documentation:

Now, reading the public key from the x509 certificate should be easy in Javascript. One option is to use ASN1 NPM package as below:

  const ASN1 = require('asn1js');
  const PKI = require('pkijs');

  const x509 = x5c[0];
  const asn1 = ASN1.fromBER((new Uint8Array(x509)).buffer); // Buffer -> ArrayBuffer
  if (asn1.offset <= 0) return Promise.reject(new Errors.BadRequest(`x509 BER Decoding Failure. ${asn1.result.error}`));
  const cert=new PKI.Certificate({ schema: asn1.result });

While the ASN1 fromBER() method loads the x509 from BER encoded buffer, the data received from attStmt of FIDO2 key may not be in primitive mode and hence needs marshalling to an ArrayBuffer using (new Uint8Array(x509)).buffer technique.

However, the PKIjs npm package is more geared towards browser usage, and for the NodeJS equivalent, the built-in CryptoAPI may be used as below:

  const Crypto = require('crypto');

  const x509 = x5c[0];
  const pem = `-----BEGIN CERTIFICATE-----\n${x509.toString("base64")}\n-----END CERTIFICATE-----`;

  const publicKey = Crypto.createPublicKey(pem);

Note the use of ES2015 template literals for creating multiline strings in javascript in a single line of code.

Developer References:

GK Palem, Blockchain Consultant
Published On: 09-Nov-2019

Gopalakrishna Palem is Technology strategist with nearly 2 decades of experience in FIDO2, DID, Blockchain Development, Artificial Intelligence, IOT, Open Source, CarMusTy, CFugue, C/C++ Music Library, Carnatic Music, Song, Notation, MIDI, Typesetting, PDF, Books, Maya, Visual Effects, DirectX, OpenGL, Simulation, Predictive Analytics, Big Data, M2M Telematics, Predictive Maintenance, Condition-based Maintenance, Research, Cryptography, Distributed Ledgers. He is a Mentor for PhD scholars and is a CTO for Hire, Consulting CTO for MVP Building, CTO for Startups, CTO as a Service, Virtual CTO, CTO Advisory Services.