microsoft / ClearScript

A library for adding scripting to .NET applications. Supports V8 (Windows, Linux, macOS) and JScript/VBScript (Windows).
https://microsoft.github.io/ClearScript/
MIT License
1.77k stars 148 forks source link

Web Crypto API support? #464

Closed thurfir closed 1 year ago

thurfir commented 1 year ago

Hi, is there a way to enable the crypto web apis https://developer.mozilla.org/en-US/docs/Web/API/Crypto in Microsoft ClearScript V8 ?

When I try to run this sample in the engine I get a ReferenceError: crypto is not defined exception:

 const array = new Uint32Array(10);
crypto.getRandomValues(array);

Tested on Microsoft.ClearScript.V8.Native.win-x64 v7.3.5

ClearScriptLib commented 1 year ago

Hi @thurfir,

ClearScript provides only the standard JavaScript built-ins. Any additional APIs must be provided by the host.

Here's a simple example that implements getRandomValues:

public sealed class Crypto {
    private readonly Random _random = new Random();
    public unsafe ITypedArray getRandomValues(ITypedArray array) {
        var size = Convert.ToInt32(array.Size);
        array.InvokeWithDirectAccess(pBytes => {
            _random.NextBytes(new Span<byte>(pBytes.ToPointer(), size));
        });
        return array;
    }
}

And then:

engine.Script.crypto = new Crypto();
engine.AddHostType(typeof(Console));
engine.Execute(@"
    const array = new Uint32Array(10);
    crypto.getRandomValues(array);
    Console.WriteLine(array.toString());
");

Good luck!

thurfir commented 1 year ago

Thanks for your help, however I am looking to generate ids, and Math.random is not a cryptographically-secure PRNG https://gist.github.com/joepie91/7105003c3b26e65efcea63f3db82dfba .

I might have to move to nodeJS from this package as there don't seems to be a JS-only way to do this.

ClearScriptLib commented 1 year ago

Hi @thurfir,

I am looking to generate ids, and Math.random is not a cryptographically-secure PRNG

The example above uses Random, which isn't cryptographically secure, but RandomNumberGenerator is cryptographically secure, to our knowledge:

public sealed class Crypto {
    public unsafe ITypedArray getRandomValues(ITypedArray array) {
        var size = Convert.ToInt32(array.Size);
        array.InvokeWithDirectAccess(pBytes => {
            RandomNumberGenerator.Fill(new Span<byte>(pBytes.ToPointer(), size));
        });
        return array;
    }
}

Cheers!

thurfir commented 1 year ago

My bad! I should have been better at reading your sample, thanks a lot!