title: BigNumber lib for Node.js gives wrong RSA decryption
body: <p>I'm trying to learn some cryptography, so I decided to take on the challenge given in the YouTube video <a href="https://youtu.be/Z8M2BTscoD4" rel="nofollow noreferrer">How the RSA algorithm works, including how to select d, e, n, p, q, and φ (phi)</a> using Node.js.</p>
  
  <p>The challenge is thus:</p>
  
  <p>Encrypt the secret using <code>m^e mod n = c</code>, and then decrypt it using <code>c^d mod n = m</code>, and then the following data is given:</p>
  
  <pre><code>// Secret Message:
  const m = 42;
  
  // Prime Numbers:
  const p = 61, q = 53;
  
  // Other numbers:
  const e = 17, n = 3233, d = 2753;
  </code></pre>
  
  <p>Sadly I quickly discovered that <code>Math.pow(c, d)</code> yields <code>Infinity</code>, so I went <code>$ npm install big-number --save</code> and did <code>BigNumber(c).pow(d)</code> instead. This yielded an actual number, but the final result after the modulus operation is still wrong. I get the number 24 when it should be 42, and I just can't for the life of me understand why (though knowing myself it's probably due to something really dumb).</p>
  
  <p>Here are the rather naïve functions I made to solve the problem:</p>
  
  <pre><code>function encryptRSA(m, e, n) {
      // return Math.pow(m, e) % n; // yields 1278 and not 2557
      return BigNumber(m).pow(e).mod(n);
  }
  </code></pre>
  
  <p>...and...</p>
  
  <pre><code>function decryptRSA(c, d, n) {
      // return Math.pow(c, d) % n; // yileded 'Infinity' so dl'd BigNumber
      return BigNumber(c).pow(d).mod(n);
  }
  </code></pre>
  
  <p>Question is, why does the last function return 24 and not 42? And how can I fix it?</p>
  
  <hr>
  
  <p>So it turns out it the solution was really dumb as expected. The number is stored backwards in the object BigNumber.number. Though when printed in a string, it is shown correctly. I still don't know why that is, though, so an answer to that would still be pretty interesting. </p>
  
  <p>I would also be extremely grateful for an answer to why the regular modulus operations yields the wrong answer, especially in the first function, though I guess it has to do with physical number length vs memory restrictions...</p>