util.uuid: Use /dev/urandom
[prosody.git] / util / uuid.lua
blob58f792fdfe6627736142b8d3841b4521595f8a54
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
9 local error = error;
10 local round_up = math.ceil;
11 local urandom, urandom_err = io.open("/dev/urandom", "r+");
13 module "uuid"
15 local function get_nibbles(n)
16 local binary_random = urandom:read(round_up(n/2));
17 local hex_random = binary_random:gsub(".",
18 function (x) return ("%02x"):format(x:byte()) end);
19 return hex_random:sub(1, n);
20 end
21 local function get_twobits()
22 return ("%x"):format(urandom:read(1):byte() % 4 + 8);
23 end
25 function generate()
26 if not urandom then
27 error("Unable to obtain a secure random number generator, please see https://prosody.im/doc/random ("..urandom_err..")");
28 end
29 -- generate RFC 4122 complaint UUIDs (version 4 - random)
30 return get_nibbles(8).."-"..get_nibbles(4).."-4"..get_nibbles(3).."-"..(get_twobits())..get_nibbles(3).."-"..get_nibbles(12);
31 end
33 function seed(x)
34 urandom:write(x);
35 urandom:flush();
36 end
38 return _M;