ethers.js/packages/random/src.ts/browser-random.ts

45 lines
1.2 KiB
TypeScript
Raw Permalink Normal View History

2019-05-14 18:25:46 -04:00
"use strict";
import { arrayify } from "@ethersproject/bytes";
2019-08-01 18:04:06 -04:00
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
2019-05-14 18:25:46 -04:00
2020-04-18 05:14:55 -04:00
let anyGlobal: any = null;
try {
anyGlobal = (window as any);
if (anyGlobal == null) { throw new Error("try next"); }
} catch (error) {
try {
anyGlobal = (global as any);
if (anyGlobal == null) { throw new Error("try next"); }
} catch (error) {
anyGlobal = { };
}
}
let crypto: any = anyGlobal.crypto || anyGlobal.msCrypto;
2019-05-14 18:25:46 -04:00
if (!crypto || !crypto.getRandomValues) {
2019-08-01 18:04:06 -04:00
logger.warn("WARNING: Missing strong random number source");
2019-05-14 18:25:46 -04:00
crypto = {
getRandomValues: function(buffer: Uint8Array): Uint8Array {
2019-08-01 18:04:06 -04:00
return logger.throwError("no secure random source avaialble", Logger.errors.UNSUPPORTED_OPERATION, {
2019-05-14 18:25:46 -04:00
operation: "crypto.getRandomValues"
});
}
};
}
export function randomBytes(length: number): Uint8Array {
2020-04-18 05:14:55 -04:00
if (length <= 0 || length > 1024 || (length % 1)) {
2019-08-01 18:04:06 -04:00
logger.throwArgumentError("invalid length", "length", length);
2019-05-14 18:25:46 -04:00
}
const result = new Uint8Array(length);
2019-05-14 18:25:46 -04:00
crypto.getRandomValues(result);
return arrayify(result);
};