1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | import haxe.io.Bytes;
|
8 | import haxe.io.BytesData;
|
9 |
|
10 | class SecureRandom {
|
11 | static public function getSecureRandomBytes (length: Int) : Bytes {
|
12 | var reason = '';
|
13 | try {
|
14 | #if flash
|
15 | return Bytes.ofData(untyped __global__["flash.crypto.generateRandomBytes"](length));
|
16 | #elseif js
|
17 | untyped __js__('var Crypto = typeof crypto === "undefined" ? require("crypto") : crypto');
|
18 | var bytes: Dynamic = untyped __js__("(Crypto.randomBytes) ? Crypto.randomBytes({0}) : Crypto.getRandomValues(new Uint8Array({0}))", length);
|
19 | var out = Bytes.alloc(length);
|
20 | for (n in 0 ... length) out.set(n, bytes[n]);
|
21 | return out;
|
22 | #elseif python
|
23 | var out = Bytes.alloc(length);
|
24 | var str = RandomOs.urandom(length);
|
25 | for (n in 0 ... length) out.set(n, str.charCodeAt(n));
|
26 | return out;
|
27 | #elseif java
|
28 | return Bytes.ofData(java.security.SecureRandom.getSeed(length));
|
29 | #elseif cs
|
30 | var out = Bytes.alloc(length);
|
31 | var rng = new cs.system.security.cryptography.RNGCryptoServiceProvider();
|
32 | rng.GetBytes(out.getData());
|
33 | return out;
|
34 | #elseif sys
|
35 | var out = Bytes.alloc(length);
|
36 | #if windows
|
37 | var input = sys.io.File.read("\\Device\\KsecDD");
|
38 | #else
|
39 | var input = sys.io.File.read("/dev/urandom");
|
40 | #end
|
41 | input.readBytes(out, 0, length);
|
42 | input.close();
|
43 | return out;
|
44 | #end
|
45 | } catch (e: Dynamic) {
|
46 | reason = '$e';
|
47 | }
|
48 | throw "Can't find a secure source of random bytes. Reason: " + reason;
|
49 | }
|
50 | }
|
51 |
|
52 | #if python
|
53 | @:pythonImport("os")
|
54 | extern class RandomOs {
|
55 | static public function urandom (count: Int) : String;
|
56 | }
|
57 | #end
|