awslabs / llrt

LLRT (Low Latency Runtime) is an experimental, lightweight JavaScript runtime designed to address the growing demand for fast and efficient Serverless applications.
Apache License 2.0
7.73k stars 341 forks source link

feat: Improved compliance of crypto object #395

Closed nabetti1720 closed 3 weeks ago

nabetti1720 commented 4 weeks ago

Description of changes

Add the following methods to improve the compliance of crypto Object.

Checklist

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

nabetti1720 commented 3 weeks ago

I might be wrong but I think it’s the view (the type array) that determines how the underlying array buffer is behaving. So it’s always a u8 array of numbers but viewed as a for example Float64Array those u8s would represent 64 bit floats instead. But it might overflow for floats in IEEE format

For this very reason, the specification does not seem to support Float32Array and Float64Array. That is to say, it may appear to be an incorrect value when viewed as a Float32Array or Float64Array.

ChatGPT seemed to know this and suggested a workaround in Javascript. :) This code also works with the current LLRT.

function getRandomFloat32Array(length) {
    var buffer = new ArrayBuffer(length * Float32Array.BYTES_PER_ELEMENT);
    var floatArray = new Float32Array(buffer);

    var uintArray = new Uint32Array(buffer);
    crypto.getRandomValues(uintArray);

    for (var i = 0; i < length; i++) {
        // Convert 32-bit unsigned integer to float between 0 and 1
        floatArray[i] = uintArray[i] / (0xFFFFFFFF + 1);
    }

    return floatArray;
}

// Example usage
var floatArray = getRandomFloat32Array(10);
console.log(floatArray);

Since we cannot find a good solution at this time, we would like to exclude Float32Array and Float64Array from support.

https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues As indicated previously, this is because support for these two Arrays is not a requirement.

I am sorry for not being able to help you.

richarddavison commented 3 weeks ago

I think we can go ahead and simply exclude support for float typed arrays

nabetti1720 commented 3 weeks ago

Thank you for your consideration. It has already been completed in the last commit.