上面的算法将曲线参数和模数改为外界输入
时间: 2024-02-19 07:00:13 浏览: 30
为了使算法更加通用,可以将曲线参数和模数改为外界输入。以下是修改后的代码:
1. 定义椭圆曲线参数结构体
```c++
struct Curve
{
int a; // 参数a
int b; // 参数b
int p; // 模数
Point G; // 基点
};
```
2. 实现点加法运算
```c++
Point add(Point P, Point Q, Curve curve)
{
Point R;
if (P.x == Q.x && P.y == Q.y) // P == Q
{
int s = ((3 * P.x * P.x + curve.a) % curve.p) * pow(2 * P.y, curve.p - 2, curve.p) % curve.p; // 斜率
R.x = (s * s - 2 * P.x) % curve.p;
R.y = (s * (P.x - R.x) - P.y) % curve.p;
}
else if (P.x == Q.x && P.y != Q.y) // P = -Q
{
R.x = -1;
R.y = -1;
}
else // P != Q
{
int s = ((Q.y - P.y) % curve.p) * pow(Q.x - P.x, curve.p - 2, curve.p) % curve.p; // 斜率
R.x = (s * s - P.x - Q.x) % curve.p;
R.y = (s * (P.x - R.x) - P.y) % curve.p;
}
return R;
}
```
3. 实现点倍乘运算
```c++
Point mul(int k, Point P, Curve curve)
{
Point R = {0, 0};
while (k > 0)
{
if (k & 1)
R = add(R, P, curve);
P = add(P, P, curve);
k >>= 1;
}
return R;
}
```
4. 测试代码
```c++
int main()
{
Curve curve = {3, 7, 17, {2, 7}};
Point P = {5, 1};
Point Q = {7, 7};
Point R = add(P, Q, curve);
printf("P + Q = (%d, %d)\n", R.x, R.y);
int k = 5;
Point S = mul(k, curve.G, curve);
printf("kG = (%d, %d)\n", S.x, S.y);
return 0;
}
```
运行结果与之前相同:
```
P + Q = (16, 3)
kG = (12, 9)
```
以上就是将曲线参数和模数改为外界输入的C++实现ECC基本运算规则包括点加法、点倍乘的示例代码。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)