Comparison

util/random.lua @ 401:7be4ebefd1f4

util.random: Use /dev/urandom or LuaCrypto
author Kim Alvefur <zash@zash.se>
date Wed, 13 Jan 2016 00:45:54 +0100
parent 388:d963c8a5d89c
comparison
equal deleted inserted replaced
399:82ad158714e5 401:7be4ebefd1f4
4 -- 4 --
5 -- This project is MIT/X11 licensed. Please see the 5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information. 6 -- COPYING file in the source package for more information.
7 -- 7 --
8 8
9 local tostring = tostring; 9 local urandom = io.open("/dev/urandom", "r");
10 local os_time = os.time;
11 local os_clock = os.clock;
12 local ceil = math.ceil;
13 local H = require "util.hashes".sha1;
14 10
15 local last_uniq_time = 0; 11 if urandom then
16 local function uniq_time() 12 return {
17 local new_uniq_time = os_time(); 13 seed = function () end;
18 if last_uniq_time >= new_uniq_time then new_uniq_time = last_uniq_time + 1; end 14 bytes = function (n) return urandom:read(n); end
19 last_uniq_time = new_uniq_time; 15 };
20 return new_uniq_time;
21 end 16 end
22 17
23 local function new_random(x) 18 local crypto = require "crypto"
24 return H(x..os_clock()..tostring({})); 19 return crypto.rand;
25 end
26
27 local buffer = new_random(uniq_time());
28
29 local function seed(x)
30 buffer = new_random(buffer..x);
31 end
32
33 local function bytes(n)
34 if #buffer < n+4 then seed(uniq_time()); end
35 local r = buffer:sub(1, n);
36 buffer = buffer:sub(n+1);
37 return r;
38 end
39
40 return {
41 seed = seed;
42 bytes = bytes;
43 };