grafana / xk6-webcrypto

WIP implementation of the WebCrypto specification for k6
GNU Affero General Public License v3.0
7 stars 4 forks source link

Let `SubtleCrypto.digest` accept strings as input #29

Open oleiade opened 1 year ago

oleiade commented 1 year ago

Problem definition

Although the specification defines the SubtleCrypto.digest operation as strictly taking ArrayBuffer instances as data parameters, [this conversation]() brought up the idea of accepting strings as a convenience too. In a standard JS runtime environment, converting from ArrayBuffer to string would be trivial using something like TextEncoder. In k6, we do not have such an API at our disposal.

Solution space

My understanding is that we have three main options:

  1. Derive from the specs to have the digest operation accept strings as input as a convenience. It is already the case in the current k6 crypto package and would be a valuable convenience for users. There are no official tests for this in the Web Platform Tests, but as Goja has native support for strings, the conversion from string to something that can be comprehended as an array of bytes by the rest of the webcrypto implementation's logic would be simple enough to test.
  2. Either expose a string to array buffer, and vice versa helper function either in the context of a jslib, or as a documentation artifact. For instance:
    
    function arrayBufferToHexString(buffer) {
    return [...new Uint8Array(buffer)]
    .map((x) => x.toString(16).padStart(2, "0"))
    .join("");
    }

function stringToArrayBuffer(s) { return Uint8Array.from(new String(s), (x) => x.charCodeAt(0)); }

oleiade commented 1 year ago

ref #8