forked from mvayngrib/react-native-randombytes
-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
54 lines (47 loc) · 1.08 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/** @format */
import "./ensureBuffer";
import sjcl from "sjcl";
type Callback = (err?: Error, buff?: Buffer) => any;
function cbWarnError(err: Error, _: Buffer = null): void {
if (err) {
console.warn("Error in react-native-randombytes", err);
}
}
function generateEntropy(): void {
if (sjcl.random.isReady()) {
return;
} else {
setTimeout(() => {
try {
const now = Date.now();
sjcl.random.addEntropy(now, 2, "random-bytes-pure.generateEntropy");
generateEntropy();
} catch (e) {
cbWarnError(e);
}
}, 1);
}
}
export function randomBytes(length, cb: Callback = cbWarnError) {
try {
const wordCount = Math.ceil(length * 0.25);
const randomBytes = sjcl.random.randomWords(wordCount);
const hexString = sjcl.codec.hex
.fromBits(randomBytes)
.substr(0, length * 2);
const toReturn = Buffer.from(hexString, "hex");
cb(null, toReturn);
return toReturn;
} catch (e) {
cb(e);
throw e;
}
}
export default randomBytes;
try {
sjcl.random.addEventListener("progress", generateEntropy);
generateEntropy();
} catch (e) {
cbWarnError(e);
throw e;
}