-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShamirSecretSharing.java
More file actions
71 lines (57 loc) · 2.33 KB
/
ShamirSecretSharing.java
File metadata and controls
71 lines (57 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ShamirSecretSharing {
public static void main(String[] args) {
// Example JSON input
Map<String, Map<String, String>> input = Map.of(
"keys", Map.of("n", "4", "k", "3"),
"1", Map.of("base", "10", "value", "4"),
"2", Map.of("base", "2", "value", "111"),
"3", Map.of("base", "10", "value", "12"),
"6", Map.of("base", "4", "value", "213")
);
BigInteger secret = findConstantTerm(input);
System.out.println("The secret constant term is: " + secret);
}
public static BigInteger findConstantTerm(Map<String, Map<String, String>> input) {
int n = Integer.parseInt(input.get("keys").get("n"));
int k = Integer.parseInt(input.get("keys").get("k"));
List<Point> points = new ArrayList<>();
// Parse and decode points
for (String key : input.keySet()) {
if (!key.equals("keys")) {
int x = Integer.parseInt(key);
int base = Integer.parseInt(input.get(key).get("base"));
String value = input.get(key).get("value");
BigInteger y = new BigInteger(value, base); // Decode y value from given base
points.add(new Point(x, y));
}
}
// Calculate the constant term (c) using Lagrange interpolation
BigInteger constantTerm = BigInteger.ZERO;
for (int i = 0; i < k; i++) {
BigInteger xi = BigInteger.valueOf(points.get(i).x);
BigInteger yi = points.get(i).y;
BigInteger term = yi;
for (int j = 0; j < k; j++) {
if (i != j) {
BigInteger xj = BigInteger.valueOf(points.get(j).x);
term = term.multiply(xj.negate()).divide(xi.subtract(xj));
}
}
constantTerm = constantTerm.add(term);
}
return constantTerm;
}
// Helper class to store (x, y) points
static class Point {
int x;
BigInteger y;
Point(int x, BigInteger y) {
this.x = x;
this.y = y;
}
}
}