[Pkg-javascript-commits] [sockjs-client] 06/350: Use window.crypto.getRandomValues when available

tonnerre at ancient-solutions.com tonnerre at ancient-solutions.com
Fri Aug 5 01:03:18 UTC 2016


This is an automated email from the git hooks/post-receive script.

tonnerre-guest pushed a commit to branch upstream
in repository sockjs-client.

commit 9f8abecb12565b83eb8b1b8b2159d5ca69cd6aaa
Author: David Benjamin <davidben at mit.edu>
Date:   Wed Jul 3 02:07:52 2013 -0400

    Use window.crypto.getRandomValues when available
    
    Issue #56. New versions of Chrome, Firefox, and Safari provide access to
    cryptographically random numbers. Change the length of random_string_chars to
    be 32 so we don't introduce biases in taking the modulus.
    
    Also make the code just index into the string, instead of doing things with
    substr.
---
 lib/utils.js | 19 +++++++++++++++----
 1 file changed, 15 insertions(+), 4 deletions(-)

diff --git a/lib/utils.js b/lib/utils.js
index f2860d4..5d0ab7e 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -6,12 +6,23 @@
  * ***** END LICENSE BLOCK *****
  */
 
-var random_string_chars = 'abcdefghijklmnopqrstuvwxyz0123456789_';
+// This string has length 32, a power of 2, so the modulus doesn't introduce a
+// bias.
+var random_string_chars = 'abcdefghijklmnopqrstuvwxyz012345';
 utils.random_string = function(length) {
     var max = random_string_chars.length;
-    var i, ret = [];
-    for(i=0; i < length; i++) {
-        ret.push( random_string_chars.substr(Math.floor(Math.random() * max),1) );
+    var i, bytes, ret = [];
+    // Use real randomness when available.
+    if (_window.crypto && _window.crypto.getRandomValues) {
+        bytes = new Uint8Array(length);
+        _window.crypto.getRandomValues(bytes);
+        for(i=0; i < length; i++) {
+            ret.push( random_string_chars[bytes[i] % max] );
+        }
+    } else {
+        for(i=0; i < length; i++) {
+            ret.push( random_string_chars[Math.floor(Math.random() * max)] );
+        }
     }
     return ret.join('');
 };

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/sockjs-client.git



More information about the Pkg-javascript-commits mailing list