Danial Ansari
Danial Ansari

Reputation: 11

Cannot compute large numbers with great precision in JavaScript

Im working on a cryptography solution which would implement Shamirs Secret Sharing, here I am generating a secret key based on the password provided by the user. These password when converted to number yield very large numbers and I would like to maintain that given we need to make the numbers hard to brute force. However, when dealing with such large numbers we need to maintain high precision and not doing so ruins the whole calculation.

Consider the following code.

let x1 = 7.188886491318616e+49
let x2 = 3544952156018063400
let y1 = 1.4377772982637232e+51
let y2 = 354495215601806340
let m = (y1-y2)/(x1-x2)
let c1 = y1-(m*x1)
let c2 = y2-(m*x2)
console.log(m,c1,c2)
20 -1.661534994731145e+35 -70544547904759460000

In the code above I'm using a linear line equation to generate constant c(which will be my secret) given 2 coordinates (x1,y1) and (x2,y2). The gradient m is being calculated as 20 according to javascript while the actual value should be 20.000000000000000000000000000000981300066289124033420383081267387768851819976318114433200550955155,
Given we are disregarding so many decimals as you can see I am getting 2 different values of c which should not be the case mathematically. The problem is javascript cannot process such precision hence the values not being accurate enough, I have already tried using Big Number and the issue is the same, is there some better standarized way to do this?

Upvotes: 1

Views: 154

Answers (1)

Heiko Theißen
Heiko Theißen

Reputation: 16728

The following code computes 100 decimal places (you gave 96):

var x1 = 71888864913186160000000000000000000000000000000000n;
var x2 = 3544952156018063400n;
var y1 = 1437777298263723200000000000000000000000000000000000n;
var y2 = 354495215601806340n;
var precision = 100;
var x = x1 - x2;
var y = y1 - y2;
var q = y / x;
var m = String(q);
var r = y - q * x;
var i = 0;
while (i++ < precision && r > 0n) {
    r *= 10n;
    q = r / x;
    m += String(q);
    r -= q * x;
}
m = BigInt(m);
var d = 10n ** BigInt(precision);
var c1 = y1 - m * x1 / d;
var c2 = y2 - m * x2 / d;
console.log("m =", m, "c1 =", c1, "c2 =", c2);

Upvotes: 0

Related Questions