Documentation

Nenad Vukicevic edited this page Jun 11, 2014 · 7 revisions

Crunch

Crunch is an arbitrary-precision integer arithmetic library for JavaScript.

It was designed to execute arithmetic operations as quickly as possible, in particular those upon which asymmetric encryption cryptosystems such as RSA are built.

Usage

Crunch can be loaded as a classic browser script

<script src="crunch.js"></script>
<script>
var crunch = Crunch();
</script>

or in a web worker

var crunch = new Worker("crunch.js");

or it can be used as a node module

npm install number-crunch
var crunch = require("number-crunch");

Example 1

x = [10, 123, 21, 127];
y = [4, 211, 176, 200];
crunch.add(x, y); //[15, 78, 198, 71]

The library accepts and returns 8-bit integer arrays which represent artbitrary-precision (big) integers, but internally it uses 28-bit arrays and performs the conversions automatically. Array radix conversion can also be performed via the transform function.

Example 2

crunch.transform([256820807]); //[15, 78, 198, 71]

The reverse transform takes a second boolean parameter

crunch.transform([15, 78, 198, 71], true); //[256820807]

Arithmetic Functions

Function Input Parameters Output
add x, y x + y
sub x, y x - y
mul x, y x * y
div x, y x / y
sqr x x * x
mod x, y x % y
exp x, e, n x^e % n
gar x, p, q, d, u, dp1, dq1 x^d % pq
inv x, y 1/x % y
xor x, y x XOR y
cut x Remove leading zeroes of x
zero x Return zero array of length x
compare x, y -1: x < y, 0: x = y, 1: x > y
decrement x x - 1
factorial n n! [n < 268435456]
nextPrime x First prime after x
testPrime x Boolean x is prime
transform x Radix conversion

Left shift lsh, right shift rsh, Barret modular reduction bmr, Miller-Rabin primality testing mrb, simple mod mds and greatest common divisor gcd are also implemented as internal methods not exposed via the initialized Crunch object.

Web Workers

Crunch can be loaded to a Web Worker. Instructions to the worker take the following format

{func: "", args: []}

Example 3

var crunch = new Worker("crunch.js");
var message = {func: "add", args: [[10, 123, 21, 127], [4, 211, 176, 200]]};

crunch.onmessage = function(m) { 
	console.log(m); 
};

crunch.postMessage(message);
Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.