-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsecretscheme.cpp
More file actions
128 lines (103 loc) · 2.41 KB
/
secretscheme.cpp
File metadata and controls
128 lines (103 loc) · 2.41 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <bits/stdc++.h>
using namespace std;
int calculate_Y(int x, vector<int>& poly)
{
int y = 0;
int temp = 1;
for (auto coeff : poly) {
y = (y + (coeff * temp));
temp = (temp * x);
}
return y;
}
void secret_sharing(int S, vector<pair<int, int> >& points,
int N, int K)
{
vector<int> poly(K);
poly[0] = S;
for (int j = 1; j < K; ++j) {
int p = 0;
while (p == 0)
p = (rand() % 997);
poly[j] = p;
}
for (int j = 1; j <= N; ++j) {
int x = j;
int y = calculate_Y(x, poly);
points[j - 1] = { x, y };
}
}
struct fraction {
int num, den;
fraction(int n, int d)
{
num = n, den = d;
}
void reduce_fraction(fraction& f)
{
int gcd = __gcd(f.num, f.den);
f.num /= gcd, f.den /= gcd;
}
fraction operator*(fraction f)
{
fraction temp(num * f.num, den * f.den);
reduce_fraction(temp);
return temp;
}
fraction operator+(fraction f)
{
fraction temp(num * f.den + den * f.num,
den * f.den);
reduce_fraction(temp);
return temp;
}
};
int Generate_Secret(int x[], int y[], int M)
{
fraction ans(0, 1);
for (int i = 0; i < M; ++i) {
fraction l(y[i], 1);
for (int j = 0; j < M; ++j) {
if (i != j) {
fraction temp(-x[j], x[i] - x[j]);
l = l * temp;
}
}
ans = ans + l;
}
return ans.num;
}
void operation(int S, int N, int K)
{
vector<pair<int, int> > points(N);
secret_sharing(S, points, N, K);
cout << "Secret is divided to " << N
<< " Parts - " << endl;
for (int i = 0; i < N; ++i) {
cout << points[i].first << " "
<< points[i].second << endl;
}
cout << "We can generate Secret from any of "
<< K << " Parts" << endl;
int M = 2;
if (M < K) {
cout << "Points are less than threshold "
<< K << " Points Required" << endl;
}
int* x = new int[M];
int* y = new int[M];
for (int i = 0; i < M; ++i) {
x[i] = points[i].first;
y[i] = points[i].second;
}
cout << "Our Secret Code is : "
<< Generate_Secret(x, y, M) << endl;
}
int main()
{
int S = 65;
int N = 4;
int K = 2;
operation(S, N, K);
return 0;
}