我一直在为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
任何人都可以帮助我吗?
答案 0 :(得分:5)
你的模数m
必须足够大。要对所有256个ASCII值进行编码和解码,它必须至少为256。
由于您在示例中使用了119,因此ASCII代码119('w'
)被视为0等等。