-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecdh.cpp
More file actions
72 lines (69 loc) · 2.54 KB
/
ecdh.cpp
File metadata and controls
72 lines (69 loc) · 2.54 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
#include "ecdh.h"
void ecdh_generate_public_key(EllipticCurve *curve,
unsigned char *in_private_key, unsigned char *out_public_key) {
EllipticCurvePoint base_point = { 0 };
unsigned char *base_x = elliptic_curve_point_get_coord_x(curve,
&base_point);
unsigned char *base_y = elliptic_curve_point_get_coord_y(curve,
&base_point);
for (unsigned long i = 0; i < curve->field_size_bytes; i++) {
base_x[i] = curve->xG[i];
base_y[i] = curve->yG[i];
}
elliptic_curve_binary_point_multiply(curve,
(EllipticCurvePoint*) out_public_key, &base_point, in_private_key,
curve->field_size_bytes);
}
int ecdh_public_key_verify(EllipticCurve *curve, unsigned char *public_key) {
unsigned long len = curve->field_size_bytes;
unsigned char *pk_x = elliptic_curve_point_get_coord_x(curve,
(EllipticCurvePoint*) public_key);
unsigned char *pk_y = elliptic_curve_point_get_coord_y(curve,
(EllipticCurvePoint*) public_key);
unsigned int is_inf = 1;
for (unsigned long i = 0; i < len; i++) {
if ((pk_x[i] != 0) || (pk_y[i] != 0)) {
is_inf = 0;
break;
}
}
if (is_inf)
return 0; //all zeroes (infinity point)
//Check if the point is on the curve
int is_on_curve = elliptic_curve_binary_point_on_curve(curve,
(EllipticCurvePoint*) public_key);
if (!is_on_curve)
return 0;
//Check if the point is in the correct subgroup
EllipticCurvePoint multiplication_result = { 0 };
unsigned char *mr_x = elliptic_curve_point_get_coord_x(curve,
&multiplication_result);
unsigned char *mr_y = elliptic_curve_point_get_coord_y(curve,
&multiplication_result);
elliptic_curve_binary_point_multiply(curve, &multiplication_result,
(EllipticCurvePoint*) public_key, curve->order,
curve->field_size_bytes);
is_inf = 1;
for (unsigned long i = 0; i < len; i++) {
if (mr_x[i] != 0 || mr_y[i] != 0) {
is_inf = 0;
break;
}
}
if (!is_inf)
return 0; //multiplication by base order didn't yield zero
return 1;
}
void ecdh_generate_shared_secret(EllipticCurve *curve,
unsigned char *in_private_key, unsigned char *in_public_key,
unsigned char *out_shared_secret) {
EllipticCurvePoint *in_public_key_point =
(EllipticCurvePoint*) in_public_key;
EllipticCurvePoint output_shared_secret = { 0 };
elliptic_curve_binary_point_multiply(curve, &output_shared_secret,
in_public_key_point, in_private_key, curve->field_size_bytes);
unsigned long len = curve->field_size_bytes;
for (unsigned long i = 0; i < len; i++) {
out_shared_secret[i] = output_shared_secret.point_mem[i];
}
}