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

34 lines
1011 B
TypeScript
Raw Normal View History

2019-05-15 01:25:46 +03:00
"use strict";
import { arrayify } from "@ethersproject/bytes";
2019-08-02 01:04:06 +03:00
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
2019-05-15 01:25:46 +03:00
export { shuffled } from "./shuffle";
let crypto: any = (<any>global).crypto || (<any>global).msCrypto;
if (!crypto || !crypto.getRandomValues) {
2019-08-02 01:04:06 +03:00
logger.warn("WARNING: Missing strong random number source");
2019-05-15 01:25:46 +03:00
crypto = {
getRandomValues: function(buffer: Uint8Array): Uint8Array {
2019-08-02 01:04:06 +03:00
return logger.throwError("no secure random source avaialble", Logger.errors.UNSUPPORTED_OPERATION, {
2019-05-15 01:25:46 +03:00
operation: "crypto.getRandomValues"
});
}
};
}
export function randomBytes(length: number): Uint8Array {
if (length <= 0 || length > 1024 || parseInt(String(length)) != length) {
2019-08-02 01:04:06 +03:00
logger.throwArgumentError("invalid length", "length", length);
2019-05-15 01:25:46 +03:00
}
const result = new Uint8Array(length);
2019-05-15 01:25:46 +03:00
crypto.getRandomValues(result);
return arrayify(result);
};