#include <iostream>
#include <stdio.h>
#include <cstring>
#include <stdlib.h>
#include <time.h>
using namespace std;
//int p,q,n,t,d,e;
/*int gcd(int x,int y)
{
return (y==0)? x:gcd(y,x%y);
}*/
/*int co_prime(int a ,int b)
{
int c;
do
{
if(b==1) return 1;
c=a%b;
a=b;
b=c;
}while(c!=0);
return 0;
} */
/*int get_p()
{
int i=2;
//srand(time(NULL));
p=rand()%100;
while(i<p && p%i!=0) i++;
if (i!=p) get_p();
else return p;
}
int get_q()
{
int i=2;
q=rand()%100;
while(i<q && q%i!=0) i++;
if (i!=q) get_q();
else return q;
}
int get_d_e()
{
get_p();
get_q();
n=p*q;
t=(p-1)*(q-1);
loop:e=rand()%t%10;
if (gcd(e,t)==e||gcd(e,t)==t) e++;
//while (co_prime(t,e)!=1) e=e+1;
for (d=2;d<t;d++)
{
if (d*e%t==1) break;
}
cout<<"p="<<p<<endl;
cout<<"q="<<q<<endl;
cout<<"t="<<t<<endl;
cout<<"d="<<d<<endl;
cout<<"e="<<e<<endl;
return d,e,n,t;
}*/
#define n 7081 //n=pq
#define t 6912 //(p-1)(q-1)
#define e 1789 //公钥
#define d 85 //私钥
typedef char strtype[10000];
int len;
long nume[10000];
int change[126];
char antichange[37];
void initialize()
{
int i;
char c;
for (i = 11, c = 'A'; c <= 'Z'; c ++, i ++)
{
change[c] = i;
antichange[i] = c;
}
}
void changetonum(strtype str)
{
int l = strlen(str), i;
len = 0;
memset(nume, 0, sizeof(nume));
for (i = 0; i < l; i ++)
{
nume[len] = nume[len] * 100 + change[str[i]];
if (i % 2 == 1) len ++;
}
if (i % 2 != 0) len ++;
}
long binamod(long numb, long k)
{
if (k == 0) return 1;
long curr = binamod (numb, k / 2);
if (k % 2 == 0)
return curr * curr % n;
else return (curr * curr) % n * numb % n;
}
long encode(long numb)
{
return binamod(numb, e);
}
long decode(long numb)
{
return binamod(numb, d);
}
main()
{
// get_d_e();
strtype str;
int i, a1, a2,input;
long curr;
initialize();
cout<<" RSA加密解密"<<endl;
cout<<"Y.加密 N.解密"<<endl;
cout<<"请选择:";
gets(str);
if (str[0] == 'Y'||str[0]=='y')
{
cout<<"请输入明文(大写字母):";
gets(str);
changetonum(str);
cout<<"加密后的密文为:";
for (i=0; i<len; i++)
{
if (i) putchar(' ');
printf(" %ld ", encode(nume[i]));
}
putchar('\n');
system("pause");
system("cls");
}
else
{
cout<<"输入密文个数:";
cin>>len;
cout<<"输入密文(十进制数字,每个密文之间用空格分隔):";
for (i = 0; i < len; i ++)
{
cin>>curr;
curr = decode(curr);
a1 = curr / 100;
a2 = curr % 100;
if (a1 != 0) putchar(antichange[a1]);
if (a2 != 0) putchar(antichange[a2]);
}
putchar('\n');
}
putchar('\n');
return 0;
}