7.7:Encrypt each of the following RSA messages x so that x is divided into blocks of integers of length 2; that is, if x = 142528,encode 14,25,and 28 separately.
RSA加密方法:y=x^E mod n
计算时可采用重复乘方法(repeated squares)
1 #include<iostream> 2 #include<algorithm> 3 #include<cstring> 4 #include<string> 5 #include<cmath> 6 #include<cstdio> 7 using namespace std; 8 9 int binary[20]; 10 double mod[20]; 11 12 int main() 13 { 14 int n,E,x; 15 while ((cin>>n>>E>>x)&&n&&E&&x) 16 { 17 memset(binary,0,sizeof(binary)); 18 memset(mod,0,sizeof(mod)); 19 for (int i=19;i>=0;i--) 20 { 21 if (1<<i <= E) 22 { 23 binary[i]=1; 24 E-= (1<<i); 25 } 26 if (E<=0.001) break; 27 } 28 mod[0]=x%n; 29 for (int i=1;i<sizeof(binary);i++) 30 { 31 mod[i]=fmod(pow(mod[i-1],2),n); 32 } 33 double temp = 1; 34 for (int i=0;i<sizeof(binary);i++) 35 { 36 if (binary[i]==1) 37 { 38 temp = fmod(fmod(temp,n)*fmod(mod[i],n),n); 39 } 40 } 41 cout<<temp<<endl; 42 } 43 return 0; 44 } 45