burnersk
burnersk

Reputation: 3480

How to create an JavaScript ArrayBuffer, that is similar to the WebAuthN's ArrayBuffer?

I am currently writing a prove of concept web application for WebAuthN (FIDO U2F, FIDO2) integration.

The data type of the returned field cred.rawId is ArrayBuffer. Within Chromes' developer console, this field is shown as here:

Chromes' developer console view on original cred.rawId data

When I try to reproduce this ArrayBuffer, I end up with this:

Chromes' developer console view on own rawId implementation

Pay attention to the "other representations" (e.g. [[Int8Array]]), which are all zero'ed out! And in addition, my ArrayBuffer looks like an ordinary array while the data is not shown (in that way) in the first original screenshot.

This is the source code (remember: PoC state) to retrieve the rawId from a stored Base64 repesentation:

function StringToByteArray(str) {
  var bytes = new ArrayBuffer();
  for (var i = 0; i < str.length; ++i) {
    var code = str.charCodeAt(i);
    var _bytes = new ArrayBuffer(bytes.byteLength + 1);
    for ( var j = 0; j < bytes.byteLength; j++ ) {
      _bytes[j] = bytes[j];
    }
    _bytes[bytes.byteLength] = code;
    bytes = _bytes
  }
  return bytes;
}

var x_rawId = StringToByteArray(base64.decode(cred.id.replace(/-/g, '+').replace(/_/g, '/').padRight(cred.id.length + (4 - cred.id.length % 4) % 4, '=')));

The Base64 class is from Nick Galbreaths' Base64 for JavaScript implementation.

The current rawId may work, however I would like to reproduce it 100% so the chance that it fails in an other browser at some future browser version is minimized.

How to achieve the representation which is shown in the Chrome screenshot?

Upvotes: 2

Views: 423

Answers (1)

vixducis
vixducis

Reputation: 1107

Could you maybe try replacing the function with the following:

function StringToByteArray(str) {
  return Uint8Array.from(str, c => c.charCodeAt(0));
}

It's very simple, but it does the trick in one of my projects.

Upvotes: 1

Related Questions