mdn/dom-examples

Web crypto stringToArrayBuffer sample implementation seems off

priyajeet opened this issue · 3 comments

Looks like these lines do nothing since buf is returned. Should return bufView? Which may also fix issues related to nodejs/node#46067 (see upstream issues linked to this issue and solutions) which was causing errors like below thrown for people using that implementation.

'importkey' on 'subtlecrypto': 2nd argument is not instance of arraybuffer, buffer, typedarray, or dataview.

Example code on this page also needs fixing as it copy/pastes the stringToArrayBuffer implementation.
https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey

Also see, where bufView is returned.
https://stackoverflow.com/questions/34814480/how-to-load-a-public-key-in-pem-format-for-encryption

@priyajeet No, returning buf is correct.

The code in question is:

  /*
  Convert a string into an ArrayBuffer
  from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String
  */
  function str2ab(str) {
    const buf = new ArrayBuffer(str.length);
    const bufView = new Uint8Array(buf);
    for (let i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return buf;
  }

As MDN:ArrayBuffer explains:

You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.

bufView is only created as an accessor used to manipulate the contents of buf. It inserts character values into buf, which is then returned once it's been populated.

(I can't speak to the correctness of the surrounding/calling code, but that function is named str2ab and that's what it does: Takes a string as input, and returns an ArrayBuffer representation of that string.)

I posted a comment on that StackOverflow answer you linked to, noting the incorrect return value in the code there.