2016-07-27 09:53:40 +03:00
|
|
|
'use strict';
|
|
|
|
|
2018-07-23 01:25:36 +03:00
|
|
|
import { arrayify } from '../utils/bytes';
|
|
|
|
import { defineReadOnly } from '../utils/properties';
|
2016-07-27 09:53:40 +03:00
|
|
|
|
2018-06-23 03:30:50 +03:00
|
|
|
let crypto: any = (<any>global).crypto || (<any>global).msCrypto;
|
2016-07-27 09:53:40 +03:00
|
|
|
if (!crypto || !crypto.getRandomValues) {
|
2017-10-20 22:13:29 +03:00
|
|
|
|
2016-07-27 09:53:40 +03:00
|
|
|
console.log('WARNING: Missing strong random number source; using weak randomBytes');
|
2017-10-20 22:13:29 +03:00
|
|
|
|
2016-07-27 09:53:40 +03:00
|
|
|
crypto = {
|
2018-06-23 03:30:50 +03:00
|
|
|
getRandomValues: function(buffer: Uint8Array): Uint8Array {
|
2017-03-08 09:51:04 +03:00
|
|
|
for (var round = 0; round < 20; round++) {
|
|
|
|
for (var i = 0; i < buffer.length; i++) {
|
|
|
|
if (round) {
|
2018-06-15 11:18:17 +03:00
|
|
|
buffer[i] ^= Math.trunc(256 * Math.random());
|
2017-03-08 09:51:04 +03:00
|
|
|
} else {
|
2018-06-15 11:18:17 +03:00
|
|
|
buffer[i] = Math.trunc(256 * Math.random());
|
2017-03-08 09:51:04 +03:00
|
|
|
}
|
|
|
|
}
|
2016-07-27 09:53:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return buffer;
|
|
|
|
},
|
|
|
|
_weakCrypto: true
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2018-06-23 03:30:50 +03:00
|
|
|
export function randomBytes(length: number): Uint8Array {
|
|
|
|
if (length <= 0 || length > 1024 || parseInt(String(length)) != length) {
|
2016-07-27 09:53:40 +03:00
|
|
|
throw new Error('invalid length');
|
|
|
|
}
|
|
|
|
|
2017-02-24 22:41:24 +03:00
|
|
|
var result = new Uint8Array(length);
|
|
|
|
crypto.getRandomValues(result);
|
2018-06-15 11:18:17 +03:00
|
|
|
return arrayify(result);
|
2016-07-27 09:53:40 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
if (crypto._weakCrypto === true) {
|
2018-06-15 11:18:17 +03:00
|
|
|
defineReadOnly(randomBytes, '_weakCrypto', true);
|
2016-07-27 09:53:40 +03:00
|
|
|
}
|