ECC椭圆曲线加密
#include <iostream>
#define Ea 20
#define Eb 4
#define Ep 29
using namespace std;
int fast_pow(int a, int b, int c)
{
int ans = 1;
a = a % c;
while (b != 0)
{
if (b & 1)
{
ans = (ans * a) % c;
}
b >>= 1;
a = (a * a) % c;
}
return ans;
}
struct point {
int x;
int y;
point():x(0),y(0){}
point(int a, int b):x(a),y(b) { }
bool operator==(const point& b) {
return this->x == b.x && this->y == b.y;
}
point operator+(const point& b) {
point result;
if (*this == b) {
long aaa = 3 * this->x * this->x + Ea;
long bbb = 2 * this->y;
//int m = (3 * this->x * this->x + Ea) / (2 * this->y) mod Ep;
long m;
if (aaa % bbb != 0) {
m = ((aaa % Ep) * fast_pow(bbb, (Ep - 2), Ep)) % Ep;
}
else {
m = (aaa / bbb) % Ep;
}
result.x = (m * m - 2 * this->x) % Ep;
result.y = (m * (this->x - result.x) - this->y) % Ep;
}
else {
long aaa = b.y - this->y;
long bbb = b.x - this->x;
if (bbb == 0) {
return point(13, 23);
}
long m;
if (aaa % bbb != 0) {
m = ((aaa % Ep) * fast_pow(bbb, (Ep - 2), Ep)) % Ep;
}
else {
m = (aaa / bbb) % Ep;
}
result.x = (m * m - this->x - b.x) % Ep;
result.y = (m * (this->x - result.x) - this->y) % Ep;
}
if (result.x < 0) {
result.x += Ep;
}
if (result.y < 0) {
result.y += Ep;
}
return result;
}
point operator-() {
this->y = Ep - this->y;
return *this;
}
};
void getG(point x,int& G) {
point Gx = x;
G = 1;
int num = 0;
do{
cout<<G<<"x:" << Gx.x << " " << Gx.y << endl;
Gx = Gx + x;
G++;
} while (Gx.x != x.x);
G++;
cout << G << "x:" << Gx.x << " " << Gx.y << endl;
}
point getNG(point x,int n) {
point result = x;
for (int i = 1; i < n; ++i) {
result = result + x;
}
return result;
}
void print(point p) {
cout << "[" << " " << p.x << "," << p.y << " " << "]" << endl;
}
int main()
{
int G;
point* x=new point(13, 23);
getG(*x, G);
cout << "阶数为:" << G << endl;
//求得G=36
//第二步,选择一个私有密钥p(p<G)
int p =25;
//第三步,公开密钥K=p*(13,23)
point K = getNG(*x, p);
//将 曲线 基点 密钥 公开
cout << "公开密钥:"<< endl;
print(K);
int msg = 13;
cout << "需要加密的信息:" << msg << endl;;
point M(13,23);
int r = 6;
point c1 = M;
for (int i = 0; i < r; ++i) {
c1 = c1 + K;
}
point c2=*x;
for (int i = 1; i < r; ++i) {
c2 = c2 + *x;
}
cout << "密文为:" << endl;;
print(c1);
print(c2);
point c3;
point c4=*x;
p = p*r % G;
for (int i = 1; i < p; ++i) {
c4 = c4 + *x;
}
c3 = c1 + (-c4);
cout << "明文为:" << c3.x << endl;
return 0;
}
|