简单实现的rsa

oujiangping [email protected]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include<iostream>
#include<stdio.h>
#include<cmath>
#include<time.h>
#include<stdlib.h>
using std::cin;
using std::cout;
using std::endl;
class Pair{
public:
Pair(){};
int e,d,n;
};
bool is_prime(int n,int *p,int c){
if(c>sqrt((double)n))
c=sqrt((double)n);
for(int i=1;i<=c;i++)
if(n%p[i]==0)
return false;
return true;
}
Pair rsa(){
while(true){
cout<<"finding......."<<endl;
bool find=true;
long begain,end;
begain=clock();
srand((int)time(0));
int n=100+rand()%100;
int *prime = new int[n];
prime[1] = 2;
int current=1;
for(int i=3;i<=n;i++){
if(is_prime(i,prime,current)){
prime[++current]=i;
}else continue;
}
int p = current-rand()%10;
int q = current-rand()%10;
while(p==q){
q = current-rand()%1;
}
p = prime[p];
q = prime[q];
n = p*q;
int f_n = (p-1)*(q-1);
int e = (int)rand()%20;
int i=0;
e=prime[e];
while((e==p)||(e==q)||(e>f_n)||(e==0)){
e = rand()%10;
i-=1;
e=prime[e];
}
int d = 1;
while(((e*d)%f_n)!=1){
d++;
end=clock();
if(end-begain>5000000){
find = false;
break;
}
}
Pair pair;
pair.e=e;
pair.d=d;
pair.n=n;
if(find)
return pair;
}
}
int Mont(int b,int e,int n){
int rt=1;
int x=b;
while(e>0){
if(e%2==1)
rt=rt*x%n;
x=x*x%n;
e/=2;
}
return rt;
}
int main(){
cout<<"Welcome to use rsa , because of the aplication don't support big number , your key will not security enough"<<endl;
Pair pair = rsa();
cout<<"YOUR PU("<<pair.e<<","<<pair.n<<")"<<endl;
cout<<"YOUR PR("<<pair.d<<","<<pair.n<<")"<<endl;
cout<<"please input an string :";
char plain[300];
int cipher[300];
fgets(plain,300,stdin);
int last = 0;
for(int i=0;i<300;i++)
if((plain[i]=='n')||(plain[i]=='