椭圆曲线密码实现D-H密钥交换的代码c语言代码,不使用OpenSSL库;
时间: 2024-02-29 07:52:25 浏览: 101
以下是一个简单的椭圆曲线密码实现D-H密钥交换的C语言代码,不使用OpenSSL库:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct point {
int x;
int y;
} point;
typedef struct curve {
int a;
int b;
int p; //质数
point g; //生成元
} curve;
int inv(int a, int m) {
int m0 = m, t, q;
int x0 = 0, x1 = 1;
if (m == 1) {
return 0;
}
while (a > 1) {
q = a / m;
t = m;
m = a % m;
a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
if (x1 < 0) {
x1 += m0;
}
return x1;
}
int mod(int a, int m) {
int r = a % m;
return r < 0 ? r + m : r;
}
point point_add(point p1, point p2, curve c) {
point res;
int s;
if (p1.x == p2.x && p1.y != p2.y) {
res.x = -1;
res.y = -1;
return res;
}
if (p1.x == p2.x) {
s = mod(3 * p1.x * p1.x + c.a, c.p) * inv(2 * p1.y, c.p) % c.p;
} else {
s = mod(p2.y - p1.y, c.p) * inv(p2.x - p1.x, c.p) % c.p;
}
res.x = mod(s * s - p1.x - p2.x, c.p);
res.y = mod(s * (p1.x - res.x) - p1.y, c.p);
return res;
}
point point_mul(point p, int k, curve c) {
point res = { -1, -1 };
while (k > 0) {
if (k % 2 == 1) {
res = res.x == -1 ? p : point_add(res, p, c);
}
p = point_add(p, p, c);
k /= 2;
}
return res;
}
void generate_key(curve c, point g, int n, int *pub_key, int *pri_key) {
srand(time(NULL));
int d = rand() % n;
*pri_key = d;
*pub_key = point_mul(g, d, c).x;
}
int main() {
curve c = { 1, 6, 11, { 2, 7 } };
int n = 17;
int alice_pub_key, alice_pri_key, bob_pub_key, bob_pri_key;
generate_key(c, c.g, n, &alice_pub_key, &alice_pri_key);
generate_key(c, c.g, n, &bob_pub_key, &bob_pri_key);
printf("Alice's public key: %d\n", alice_pub_key);
printf("Bob's public key: %d\n", bob_pub_key);
int alice_shared_key = point_mul({ bob_pub_key, 0 }, alice_pri_key, c).x;
int bob_shared_key = point_mul({ alice_pub_key, 0 }, bob_pri_key, c).x;
printf("Alice's shared key: %d\n", alice_shared_key);
printf("Bob's shared key: %d\n", bob_shared_key);
return 0;
}
```
其中,curve结构体表示椭圆曲线的参数,point结构体表示椭圆曲线上的点。inv函数和mod函数分别实现了求逆元和模运算。point_add函数实现了椭圆曲线上点的加法,point_mul函数实现了椭圆曲线上点的倍乘。generate_key函数实现了密钥生成过程。在main函数中,我们使用curve结构体定义了一个椭圆曲线,使用generate_key函数生成了Alice和Bob的公私钥,并计算了他们的共享密钥。
阅读全文