/deterministic-rsa-js

Deterministic RSA using vanilla JavaScript

Primary LanguageJavaScriptMIT LicenseMIT

WARNING! This project has not yet been verified to be cryptographically secure. USE AT YOUR OWN RISK!

deterministic-rsa-js

Deterministic RSA using vanilla JavaScript

Can be used to generate RSA keys based on mnemonic keys. This functionality is already possible using the node-forge package however, this project is ~3 times faster making it more suitable for high performance applications or real-time interactive environments.

Available on npm

How it works

Native BigInt, no byte array shims

The original version of this project used Rust which took ~1.3s to generate a key natively, however when compiled to WASM, it took ~15 seconds. This is a because the WASM implementation used Uint8Array as a shim for large integers which is very slow in JavaScript. In the current implementation, we use JS native BigInts which handles arbitrarily-precise integers at a native level. This is where most of the speed up comes from.

Multithreading

Using workerpool, we are able to deterministically generate primes in parallel. This results in a 50% speedup on average.

Fast random number generation

Use simple 32bit math and bitwise operators. Instead of generating entirely new numbers, simply pick a random bit between 1 and nBits - 3 then ^= 1n << bitShift it (lbitshift xor assign). This reduces how many times we need to run the number generation.

Optimized memory behavior

Preallocate buffers and variables to reduce garbage collection. We also take care to only compare and assign values of the same type in order remove the performance cost of type coercion and dynamic memory allocation.

Testing

To test, run node test

TODO

  • Add optimized prime checking implementation
  • Add native Node crypto
    • When running, we should check if the node crypto module is available. If it is, we use crypto.checkPrime() to leverage the native C++ prime checking. Otherwise, we fallback to our JavaScript solution.
  • Alternative PRNG
    • Using different PRNG and bit chunking methods may result in a performance increase, though it can vary wildly depending on the browser or runtime environment.

Resources