randombytes
randombytes copied to clipboard
Support Electron apps
https://github.com/dsprenkels/randombytes/blob/1c0c6665640535a9a851bf5c2df2e0369273b6ad/randombytes.c#L302
The code under randombytes_js_randombytes_nodejs doesn't seem to work for Electron apps webassembly. Since many implementations don't check for return value of randombytes, downstream code was silently passing and causing security issues.
We have an updated version for randombytes_js_randombytes_nodejs that worked for electronjs app as well (as per Mozilla docs, window.crypto is a CSPRNG) https://developer.mozilla.org/en-US/docs/Web/API/Crypto
Example: https://github.com/DogeProtocol/hybrid-pqc/blob/d13f9d3944515ccdd7eee4fe98b08562b71564ef/random/randombytes.c#L322C1-L327C4
`#if defined(EMSCRIPTEN) static int randombytes_js_randombytes_nodejs(void *buf, size_t n) {
const int ret = EM_ASM_INT({
if (window.crypto && window.crypto.getRandomValues) {
var randBuffer = new Uint8Array($1);
window.crypto.getRandomValues(randBuffer);
writeArrayToMemory(randBuffer, $0);
return 0;
}
var cryptoMod;
try {
cryptoMod = require('crypto');
} catch (error) {
return -2;
}
try {
writeArrayToMemory(cryptoMod.randomBytes($1), $0);
return 0;
} catch (error) {
return -1;
}
}, buf, n);
switch (ret) {
case 0:
return 0;
case -1:
errno = EINVAL;
return -1;
case -2:
errno = ENOSYS;
return -1;
}
return -3;
assert(false); // Unreachable
} #endif /* defined(EMSCRIPTEN) */`