-
Notifications
You must be signed in to change notification settings - Fork 987
Arithmetic
(This page is written at a slightly higher level than the rest of the wiki.)
Underlying SJCL's ECC module are fully functional big number and elliptic curve arithmetic libraries which can implement tons of other cryptosystems from textbook RSA to elliptic curve ElGamal encryption. This page is intended to be an introduction to using the libraries and an overview of what they're capable of.
The big number library in SJCL is fairly intuitive if you've ever worked with big numbers in other languages: they have to be initialized with either a javascript Number
, a hexadecimal string, or another sjcl.bn
object. Alternatively, you can call .toString()
on a sjcl.bn
object and get the number in hexadecimal.
var a = new sjcl.bn(100)
var b = new sjcl.bn("0x64")
a.toString() // 0x64
They can also work a bit like codecs in that you can call .toBits()
on a sjcl.bn
object and get a bit array which is compatible with the sjcl.bn.fromBits
function. (The .toString()
method isn't compatible with sjcl.bn.fromBits
, even through the hex codec.)
Along with a few notes, the rest of the library is fairly easy to figure out from the technical documentation.
- All methods return their output. Methods that end with an
M
don't copythis
to a separate variable, so it will change to the value that's returned. The same function without the M ensures thatthis
remains the same after it's called. - 'Normalizing' means propagating carries. You only need to call the
.normalize()
or.cnormalize()
after doing a batch of addition or subtraction.
And as another little sanity test, here's part of a toy RSA implementation:
// Define RSA parameters.
var p = new sjcl.bn(6307),
q = new sjcl.bn(7919),
N = p.mul(q)
var e = new sjcl.bn(3)
// Chinese Remainder Theorem
// Calculate d, the inverse of e mod N
var a = e.inverseMod(p),
b = e.inverseMod(q)
var r = a.sub(b).normalize().mul(q.inverseMod(p)),
d = b.add(q.mul(r)).normalize().mod(N)
console.log("Calculated d:", d.toString())
// Verify
var one = new sjcl.bn(1),
test = e.mulmod(d, N)
console.log("Inverses? ", test.equals(one))
// Output:
// Calculated d: 0xfe08ba
// Good? true