C的RSA密码算法实现
C写的,囧,网络课本上看过,对于我这种数学白痴怎么可能会?拖住wekooo要了公式,随便写写……
对于转ascii码的时候太囧,char最大到127,超过就变负数了,经常出乱码,太郁闷,后面改成unsigned char,在p=11,q=13的情况下可以成功转换a-z0-9的内容……
-
#include<stdio.h>
-
-
int gcd(int a, int b){
-
return b==0?a:gcd(b,a%b);
-
}
-
-
int getE(int t, int n){
-
int e = 2;
-
while(e<n&&gcd(e,t)!=1)e++;
-
return e;
-
}
-
-
int getD(int t, int e){
-
int d = 1;
-
while(((e*d)%t)!=1)d++;
-
return d;
-
}
-
-
int pow(int x, int e, int n){
-
int s = 1;
-
while(e--){
-
s*=x;
-
s%=n;
-
}
-
return s;
-
}
-
-
unsigned char rsa(unsigned char c, int e, int n){
-
return pow(c, e, n);
-
}
-
-
int main(){
-
int p,q;
-
int n;
-
int e,d;
-
int i;
-
char filePath[100];
-
unsigned char word[1000], en_word[1000], de_word[1000];
-
FILE *fp,*fc;
-
-
scanf("%d%d",&p,&q);
-
-
n = p*q;
-
-
e = getE((p-1)*(q-1),n);
-
-
d = getD((p-1)*(q-1),e);
-
-
scanf("%s",filePath);
-
-
fp=fopen(filePath, "r");
-
fc=fopen("encrypted.txt", "w");
-
-
while(fscanf(fp,"%s",word)!=EOF){
-
for(i=0; word[i]!='\0'; i++) en_word[i] = rsa(word[i], e, n);
-
en_word[i] = '\0';
-
fprintf(fc,"%s", en_word);
-
}
-
fclose(fp);
-
fclose(fc);
-
-
fp=fopen("encrypted.txt", "r");
-
fc=fopen("decrypted.txt", "w");
-
while(fscanf(fp,"%s",word)!=EOF){
-
for(i=0; word[i]!='\0'; i++) de_word[i] = rsa(word[i], d, n);
-
de_word[i] = '\0';
-
fprintf(fc,"%s", de_word);
-
}
-
fclose(fp);
-
fclose(fc);
-
-
return 0;
-
}
wekooo大牛说e一般是选的3,如果(p-1)*(q-1)不为3的倍数的话。
这里且先不管 = =。p、q输入质数且128<p*q<256为佳……
不然会出bug 囧rz ……