Javascript SDK of WoopChain protocol
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
sdk/packages/harmony-crypto/src/random.ts

29 lines
838 B

/**
* @function randomBytes
* @description Uses JS-native CSPRNG to generate a specified number of bytes.
* NOTE: this method throws if no PRNG is available.
* @param {Number} bytes bytes number to generate
* @return {String} ramdom hex string
*/
export const randomBytes = (bytes: number): string => {
let randBz: number[] | Uint8Array;
if (
typeof window !== 'undefined' &&
window.crypto &&
window.crypto.getRandomValues
) {
randBz = window.crypto.getRandomValues(new Uint8Array(bytes));
} else if (typeof require !== 'undefined') {
randBz = require('crypto').randomBytes(bytes);
} else {
throw new Error('Unable to generate safe random numbers.');
}
let randStr = '';
for (let i = 0; i < bytes; i += 1) {
randStr += `00${randBz[i].toString(16)}`.slice(-2);
}
return randStr;
};