diff options
author | Fraser Adams <fraser.adams@blueyonder.co.uk> | 2014-01-02 16:40:09 +0000 |
---|---|---|
committer | Fraser Adams <fraser.adams@blueyonder.co.uk> | 2014-01-02 16:40:09 +0000 |
commit | 385a660a1868dc1777b251dfcf83371ccd388b02 (patch) | |
tree | c254e924656076501441b607364e2a67232e419d /src | |
parent | 32e1d73d605a7c4c3dc162b7c0d626b3dcce27ce (diff) |
Added crypto quality random number generators for Node.js and browser environment if available
Diffstat (limited to 'src')
-rw-r--r-- | src/library_uuid.js | 30 |
1 files changed, 24 insertions, 6 deletions
diff --git a/src/library_uuid.js b/src/library_uuid.js index 0c1bdf91..cce0a4f8 100644 --- a/src/library_uuid.js +++ b/src/library_uuid.js @@ -27,12 +27,30 @@ mergeInto(LibraryManager.library, { // tweaked slightly in order to use the 'compact' UUID form used by libuuid. uuid_generate: function(out) { // void uuid_generate(uuid_t out); - var uuid = new Array(16); - var d = new Date().getTime(); - for (var i = 0; i < 16; i++) { - var r = (d + Math.random()*256)%256 | 0; - d = Math.floor(d/256); - uuid[i] = r; + var uuid = null; + + if (ENVIRONMENT_IS_NODE) { + // If Node.js try to use crypto.randomBytes + try { + var rb = require('crypto').randomBytes; + uuid = rb(16); + } catch(e) {} + } else if (typeof(window.crypto) != 'undefined' && + typeof(window.crypto.getRandomValues) != 'undefined') { + // If crypto.getRandomValues is available try to use it. + uuid = new Uint8Array(16); + window.crypto.getRandomValues(uuid); + } + + // Fall back to Math.random if a higher quality random number generator is not available. + if (!uuid) { + uuid = new Array(16); + var d = new Date().getTime(); + for (var i = 0; i < 16; i++) { + var r = (d + Math.random()*256)%256 | 0; + d = Math.floor(d/256); + uuid[i] = r; + } } uuid[6] = (uuid[6] & 0x0F) | 0x40; |