C/C++代码
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
int power(int a, int b)
{
int temp = a;
for(int i=1 ; i<b ; i++)
{
temp = temp * a;
}
return temp;
}
bool Prime(int a)
{
for(int i=2 ; i<= (a/2) ; i++)
{
if((a % i) == 0)
{
return false;
}
}
return true;
}
int gcd(int a , int b)
{
while(b!=0)
{
int temp = a % b;
a = b;
b = temp;
}
return a;
}
int euler(int a)
{
int b = 0;
for(int i=1 ; i<a ; i++)
{
if(gcd(a,i) == 1)
{
b += 1;
}
}
return b;
}
int order(int a, int n, int b)
{
int p = 1;
while( p<=n && power(b,p%a) != 1)
{
p += 1;
}
p = p - 1;
if (p <= n)
{
return p;
}
else
{
return -1;
}
}
int Generate_p()
{
srand((unsigned int)time(NULL));
int p = (rand() % (10000 - 1000 + 1) + 1000);
for(; p<10000 ; p++)
{
if (Prime(p)==true)
{
return p;
}
}
}
int Generate_g(int p)
{
int n = euler(p);
for(int a = 2; a<p ; a++)
{
if(order(p,n,a) == n)
{
return a;
}
}
}
int Generate_d(int p)
{
srand((unsigned int)time(NULL));
int d = rand() % ( p-2-2+1) + 2;
return d;
}
int modpow(long long a, long long b, int c)
{
int res = 1;
while(b > 0)
{
if(b & 1)
{
res = (res * a) % c;
}
b = b >> 1;
a = (a * a) % c;
}
return res;
}
int inverse(int num,int mod)
{
int a = num;
int b = mod;
int x = 0, y = 1, x0 = 1, y0 = 0;
int qt, temp;
while(b != 0)
{
qt = a / b;
temp = a % b;
a = b;
b = temp;
temp = x; x = x0 - qt * x; x0 = temp;
temp = y; y = y0 - qt * y; y0 = temp;
}
if(x0 < 0)
{
x0 += mod;
}
return x0;
}
void Encryption(int y, int g, int p, int m, int &C1, int &C2)
{
int r;
int temp;
int c1, c2;
srand((unsigned)time(NULL));
r = rand();
c1 = modpow(g, r, p);
temp = modpow(y, r, p);
c2 = (m * temp)%p;
cout << "加密后结果(密文对): " << "{" << c1 << "," << c2 << "}" << endl;
C1 = c1;
C2 = c2;
}
int Decryption(int c1, int c2, int d, int p)
{
int temp;
temp = modpow(c1, d, p);
int temp1 = inverse(temp, p);
int m = (c2*temp1)%p;
return m;
}
int main()
{
int m = 2;
int p = Generate_p();
int g = Generate_g(p);
int d = Generate_d(p);
cout << "3. Elgamel算法(随机生成域参数、随机生成密钥对、加密、解密)" << endl;
cout << endl;
cout << "明文m的内容为: " << m << endl;
cout << endl;
cout << "公钥为:" << endl;
cout << "y: " << modpow(g,d,p) << endl;
cout << "g: " << g << endl;
cout << "p: " << p << endl;
cout << endl;
cout << "密钥为:" << endl;
cout << "d: " << d << endl;
cout << endl;
int c1,c2 ;
Encryption(modpow(g,d,p),g,p,m,c1,c2);
cout <<"解密后的结果为: " << Decryption(c1,c2,d,p) << endl;
cout << endl;
system("pause");
return 0;
}
运行结果
![运行结果](https://img-blog.csdnimg.cn/e2ae50cea81a4fc5b3a05911c4a311b3.png)