From abf054520802f83e57cc98b85229d41259ffabaf Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Thomas=20Obernd=C3=B6rfer?= <toberndo@yarkon.de>
Date: Sat, 18 Jan 2014 16:37:15 +0100
Subject: [PATCH] Change internal representation of random data from
 Uint32Array to Uint8Array

---
 src/crypto/random.js      | 27 +++++++++++++++++----------
 src/worker/async_proxy.js |  6 +++---
 2 files changed, 20 insertions(+), 13 deletions(-)

diff --git a/src/crypto/random.js b/src/crypto/random.js
index 51caad81..cbe76bd5 100644
--- a/src/crypto/random.js
+++ b/src/crypto/random.js
@@ -60,30 +60,37 @@ module.exports = {
    * @return {Integer} A secure random number
    */
   getSecureRandom: function(from, to) {
-    var buf = new Uint32Array(1);
-    this.getRandomValues(buf);
+    var randUint = this.getSecureRandomUint();
     var bits = ((to - from)).toString(2).length;
-    while ((buf[0] & (Math.pow(2, bits) - 1)) > (to - from))
-      this.getRandomValues(buf);
-    return from + (Math.abs(buf[0] & (Math.pow(2, bits) - 1)));
+    while ((randUint & (Math.pow(2, bits) - 1)) > (to - from)) {
+      randUint = this.getSecureRandomUint();
+    }
+    return from + (Math.abs(randUint & (Math.pow(2, bits) - 1)));
   },
 
   getSecureRandomOctet: function() {
-    var buf = new Uint32Array(1);
+    var buf = new Uint8Array(1);
     this.getRandomValues(buf);
-    return buf[0] & 0xFF;
+    return buf[0];
+  },
+
+  getSecureRandomUint: function() {
+    var buf = new Uint8Array(4);
+    var dv = new DataView(buf.buffer);
+    this.getRandomValues(buf);
+    return dv.getUint32(0);
   },
 
   /**
    * Helper routine which calls platform specific crypto random generator
-   * @param {Uint32Array} buf
+   * @param {Uint8Array} buf
    */
   getRandomValues: function(buf) {
     if (typeof window !== 'undefined' && window.crypto) {
       window.crypto.getRandomValues(buf);
     } else if (nodeCrypto) {
-      var bytes = nodeCrypto.randomBytes(4);
-      buf[0] = (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3];
+      var bytes = nodeCrypto.randomBytes(buf.length);
+      buf.set(bytes);
     } else if (this.randomBuffer.buffer) {
       this.randomBuffer.get(buf);
     } else {
diff --git a/src/worker/async_proxy.js b/src/worker/async_proxy.js
index 6a8212a4..2b44880e 100644
--- a/src/worker/async_proxy.js
+++ b/src/worker/async_proxy.js
@@ -76,13 +76,13 @@ AsyncProxy.prototype.seedRandom = function(size) {
 };
 
 /**
- * Get Uint32Array with random numbers
+ * Get Uint8Array with random numbers
  * @param  {Integer} size Length of buffer
- * @return {Uint32Array}
+ * @return {Uint8Array}
  */
 AsyncProxy.prototype.getRandomBuffer = function(size) {
   if (!size) return null;
-  var buf = new Uint32Array(size);
+  var buf = new Uint8Array(size);
   crypto.random.getRandomValues(buf);
   return buf;
 };