Use DOM random generator if available

This commit is contained in:
Franck Royer 2021-07-09 15:48:25 +10:00
parent 1f6ed9b525
commit b70f7c5a95
No known key found for this signature in database
GPG Key ID: A82ED75A8DFC50A4
2 changed files with 20 additions and 5 deletions

View File

@ -1,5 +1,4 @@
import { Buffer } from 'buffer';
import { randomBytes } from 'crypto';
import * as crypto from 'crypto';
import ecies from 'ecies-parity';
@ -127,7 +126,7 @@ export async function decryptAsymmetric(
* Generate a new private key
*/
export function generatePrivateKey(): Uint8Array {
return crypto.randomBytes(32);
return randomBytes(32);
}
/**
@ -161,12 +160,18 @@ function getSizeOfPayloadSizeField(payload: Uint8Array): number {
return s;
}
function validateDataIntegrity(value: Buffer, expectedSize: number): boolean {
function validateDataIntegrity(
value: Uint8Array,
expectedSize: number
): boolean {
if (value.length !== expectedSize) {
return false;
}
if (expectedSize > 3 && value.equals(Buffer.alloc(value.length))) {
if (
expectedSize > 3 &&
Buffer.from(value).equals(Buffer.alloc(value.length))
) {
return false;
}
@ -193,3 +198,13 @@ function ecRecoverPubKey(messageHash: string, signature: Buffer): Uint8Array {
false
);
}
function randomBytes(length: number): Uint8Array {
if (typeof window !== 'undefined' && window && window.crypto) {
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);
return array;
} else {
return crypto.randomBytes(length);
}
}

View File

@ -41,7 +41,7 @@
// "experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
// "emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */,
"lib": ["es2017"],
"lib": ["es2017", "dom"],
"types": ["node", "mocha"],
"typeRoots": ["node_modules/@types", "src/types"]
},