【文件属性】:
文件名称:RSA算法代码
文件大小:1KB
文件格式:RAR
更新时间:2018-02-05 03:21:56
RSA算法
网络安全中的经典问题,RSA算法。#include
#include
int sushupanduan(int a, int b)
{
int s,i,f,g;
s = sqrt(a);
for(i = 2; i <= s; i++)
if(a % i == 0)
break;
if(i > s)
f=1;
else
return 0;
s = sqrt(b);
for(i = 2; i <= s; i++)
if(b % i == 0)
break;
if(i > s)
g = 1;
else
return 0;
if(f == 1 && g == 1)
return 1;
return 0;
}
int husu(int a, int b)
{
if(a % b == 0)
return b;
else
husu(b,a%b);
}
int find_e(int m)
{
int e;
for(e = 4; e < m; e++)
{
if(husu(e,m) == 1)
break;
else
continue;
}
return e;
}
int find_d(int e, int m)
{
int d;
for(d = m / e + 1; d < m; d++)
{
if(d * e % m == 1)
break;
else
continue;
}
return d;
}
int quick(int a,int b,int n)
{
int c = 0,f = 1,k = 0,i;
int er[50];
while(b > 0)
{
er[k] = b % 2;
b = b / 2;
k++;
}
for(i = k;i >= 0;i--)
{
c = 2 * c;
f = (f * f) % n;
if(er[i] == 1)
{
c = c + 1;
f = (f * a) % n;
}
}
return f;
}
main()
{
int p,q,f,n,m,e,d,M,rsa_jia,rsa_jie;//f为标志,m为ψ(n),其余变量均与书上相同.
printf("请输入两个比较大的素数p,q(用,隔开):");
scanf("%d,%d",&p,&q);
printf("\n");
f = sushupanduan(p,q);
if(f == 0)
{
printf("您输入的p,q中有不为素数的数,请重新输入:");
scanf("%d,%d",&p,&q);
printf("\n");
}
else
{
n = p * q;
m = (p-1) * (q-1);
}
e = find_e(m);
d = find_d(e,m);
printf("公钥:={%d,%d}\n",e,n);
printf("私钥:={%d,%d}\n",d,n);
printf("请输入明文M:");
scanf("%d",&M);
rsa_jia = quick(M,e,n);
printf("加密:%d\n",rsa_jia);
rsa_jie = quick(rsa_jia,d,n);
printf("解密:%d\n",rsa_jie);
}
【文件预览】:
RSA.c
RSA算法.txt