Software /
code /
prosody
Comparison
util/random.lua @ 7050:ae044691de0f
util.random: Use /dev/urandom
author | Kim Alvefur <zash@zash.se> |
---|---|
date | Wed, 06 Jan 2016 03:28:56 +0100 |
parent | 6421:c3011ab945b8 |
child | 7083:ac920b0f9eae |
comparison
equal
deleted
inserted
replaced
7049:0eee56075901 | 7050:ae044691de0f |
---|---|
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 = assert(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".sha512; | |
14 | |
15 local last_uniq_time = 0; | |
16 local function uniq_time() | |
17 local new_uniq_time = os_time(); | |
18 if last_uniq_time >= new_uniq_time then new_uniq_time = last_uniq_time + 1; end | |
19 last_uniq_time = new_uniq_time; | |
20 return new_uniq_time; | |
21 end | |
22 | |
23 local function new_random(x) | |
24 return H(x..os_clock()..tostring({})); | |
25 end | |
26 | |
27 local buffer = new_random(uniq_time()); | |
28 | 10 |
29 local function seed(x) | 11 local function seed(x) |
30 buffer = new_random(buffer..x); | 12 urandom:write(x); |
13 urandom:flush(); | |
31 end | 14 end |
32 | 15 |
33 local function bytes(n) | 16 local function bytes(n) |
34 if #buffer < n+4 then seed(uniq_time()); end | 17 return urandom:read(n); |
35 local r = buffer:sub(1, n); | |
36 buffer = buffer:sub(n+1); | |
37 return r; | |
38 end | 18 end |
39 | 19 |
40 return { | 20 return { |
41 seed = seed; | 21 seed = seed; |
42 bytes = bytes; | 22 bytes = bytes; |