我一直在为 RSA 算法编写代码。它运作良好,但不幸的是它显示了小“w”、“z”、“x”、“y”的错误答案。
我的加密算法很简单。使用两个不同的素数和“e”生成公钥,然后通过生成“d”创建私钥。然后使用 BIGMOD(快速求幂)算法,我只计算模数部分来加密和解密。这是我的代码:
#include<stdio.h>
#include<string.h>
long long int square(long long int a);
long long int BigMod(int M,int E,int N);
void encrypt(int l,int E,int N);
void decrypt(int E,int N );
int main()
{
main_RSA();
return 0;
}
void main_RSA()
{
int p,q;
printf("Write two distinct Prime number separated by space:");
scanf("%d %d",&p,&q);
int n=p*q;
int phi=(p-1)*(q-1);
int e;
printf("Enter a prime number 'e' as GCD(e,(P-1)*(Q-1)) : ");
scanf("%d",&e);
printf("public key( e , n ) : ( %d %d )\n",e,n);
int d,RES=-1;
for(d=1;;d++){
RES=(d*e)%phi;
if(RES==1)break;
}
printf("Private Key( d,n ) : ( %d %d )\n",d,n);
printf("Please input your string : ");
char arr[1000000];
fflush(stdin);
gets(arr);
int i;
FILE *fp=fopen("RSAlog.dll","w");
fclose(fp);
for(i=0;arr[i];i++){
int ASCII=arr[i];
encrypt(ASCII,e,n);
}
printf("\n");
FILE *fpp=fopen("RSAlog.dll","a");
fprintf(fp,"-1");
fclose(fpp);
decrypt(d,n);
}
long long int BigMod(int b,int p,int m) //b^p%m=?
{
if(p==0)return 1;
else if(p%2==0)return square(BigMod(b,p/2,m))%m;
else return ((b % m) * BigMod(b,p-1,m)) % m;
}
long long int square(long long a)
{
return a*a;
}
void encrypt(int m ,int e,int n){
FILE *fp;
fp=fopen("RSAlog.dll","a");
int c=BigMod(m,e,n);
printf("%d ",c) ;
fprintf(fp,"%d ",c);
fclose(fp);
}
void decrypt(int d,int n){
FILE *fp;
fp=fopen("RSAlog.dll","r");
while(1){
int c;
fscanf(fp,"%d",&c);
//printf("%d ",c);
if(c==-1)break;
int m=BigMod(c,d,n);
printf("%c",m);
}
}
输出:
Write two distinct Prime number separated by space:7 17
Enter a prime number 'e' as GCD(e,(P-1)*(Q-1)) : 5
public key( e , n ) : ( 5 119 )
Private Key( d,n ) : ( 77 119 )
Please input your string : the quick brown fox runs over the lazy dog
114 83 33 2 78 87 56 29 116 2 98 88 76 0 94 2 51 76 1 2 88 87 94 47 2 76 118 33 88 2 114 83 33 2 75 20 5 32 2 53 76 52
the quick bro n fo☺ runs over the la♥☻ dog
有谁能够帮助我?