title: Browserify `crypto.createDecipher` "Uncaught RangeError: Invalid array length"
body: <p>I have a crypto code sample that works in Node, but when I try it in browserify, I get a "Uncaught RangeError: Invalid array length"</p>
  
  <pre><code>var crypto = require("crypto");
  
  function encrypt(data, key, algorithm, encoding) {
      algorithm = algorithm || "aes256";
      encoding = encoding || "base64";
      var cipher = crypto.createCipher(algorithm, key);
      return cipher.update(data, "utf8", encoding) + cipher.final(encoding);
  }
  
  function decrypt(data, key, algorithm, encoding) {
      algorithm = algorithm || "aes256";
      encoding = encoding || "base64";
      var decipher = crypto.createDecipher(algorithm, key);
      return decipher.update(data, encoding, "utf8") + decipher.final("utf8");
  }
  
  var key = "this is a very secure key";
  var data = "The quick brown fox jumps over the lazy dog.";
  
  var encryptedData = encrypt(data, key);
  console.log("Encrypted: ", encryptedData);
  
  var decryptedData = null;
  try {
      decryptedData = decrypt(encryptedData, key);
      console.log("Decrypted: ", decryptedData);
  } catch (ex) {
    console.log("Oops!", ex.stack);
  }
  
  if (data === decryptedData) {
    console.log("It worked!");
  } else {
    console.log("Something went terribly wrong, my friend.");
  }
  </code></pre>
  
  <p>Output from Node:</p>
  
  <pre><code>$ node crypto.js
  Encrypted:  ClvTr5IWbgLHmgGQi81T6xtCR1RX4j5prSvFmtFr9+EXr5qKePKWcnu4tdFckh50
  Decrypted:  The quick brown fox jumps over the lazy dog.
  It worked!
  </code></pre>
  
  <p>Output from Browserify:</p>
  
  <pre><code>Encrypted:  ClvTr5IWbgLHmgGQi81T6xtCR1RX4j5prSvFmtFr9+E=F6+ainjylnJ7uLXRXJIedA==
  Oops! RangeError: Invalid array length
  </code></pre>
  
  <p>A few interesting observations:</p>
  
  <ol>
  <li>The encrypted output is different right after <code>Fr9+E</code> (about 43 chars in) leading me to think that the issue is in the encryption and not the decryption.</li>
  <li>It works if I choose a smaller string for <code>data</code> such as "testing".</li>
  </ol>
  
  <p>The entire code is on <a href="http://requirebin.com/?gist=66e1baa0f206f9a184c9" rel="nofollow">RequireBin</a>. Anything you can do to point me in the right direction to getting this solved would be appreciated.</p>
  
  <h3>Update</h3>
  
  <p>If I add the following line of code just before calling <code>decrypt</code> (i.e. decrypt Node's encrypted data) it works. Proving my point that the error lies in the encryptor.</p>
  
  <p><code>
  encryptedData = "ClvTr5IWbgLHmgGQi81T6xtCR1RX4j5prSvFmtFr9+EXr5qKePKWcnu4tdFckh50";
  </code></p>
  
  <h3>Update 2</h3>
  
  <p>Setting the algorithm to <code>aes-256-ctr</code> will make my test pass in Browserify, but I'm still concerned that browserify-crypto's <code>aes256</code> yields different a different result than Node's.</p>