# include <iostream.h>
# include <string.h>
# include <fstream.h>
# include <math.h>
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
# define ul int
//Fungsi cek prima atau bukan
ul isPrime(ul n)
{
 ul b=1;
 for(ul i=2;i<n;i++)
  if(n%i==0) { b=0; break; }
 return b;
}
//Fungsi pangkat
ul Power(ul x,ul y)
{
 ul ans=1;
 if(x==1) return x;
 for(ul i=1;i<=y;i++)
   ans*=x;
 return(ans);
}
//Fungsi ubah ke binary untuk key e dan d method2
char * ToBin(int x)
{
char *ans=new char[20];
int i=0;
 while(x>=1)
 {
  if(x%2==1) ans[i]=’1′; else ans[i]=’0′;
  x/=2; i++;
 }
 if(x==1) ans[i]=’1′,i++;
 ans[i]=”;
 strrev(ans);
 return(ans);
}
//Fungsi encrypt dan decrypt (x^y)%z //Pake Method 3
ul Crypt(int x,int key,int n) {
char *B=new char[20];
B=ToBin(key);
int ans,i;
ans=x;
i=strlen(B)-1;
//int c=1;
while (B[i]!=1)
{
i=i-1;
}
for (int j=i-1;j>0;j–){
ans=(ans*ans)%n;
if(B[j]==’1′)
  {
    ans=(ans*x)%n;
  }
}
return (ans);
}
void main()
{
/* K E Y   G E N E R A T I O N */
 int p,q,n,n1,e,d;
 Beg:    
 // Reading 2 random prime-numbers from 20 to 50
 p=20+rand()%150;
 q=20+rand()%150;
 if(p==q||!isPrime(p)||!isPrime(q)) goto Beg;
 n = p * q;
 n1 = (p-1) * (q-1);
 int x=n1+1;
 for(e=2;e<=(x/2);e++)
 {
  if(x%e==0) break;
 }
  d=x/e;
 if(p==1||q==1||e==1||d==1||e==d||q==e||q==d||p==e||p==d) goto Beg;
 cout<<endl;
 cout<<“RSA CODE”<<endl;
 cout<<“=================================================”<<endl;
 cout<<“p        = “<<p<<endl;
 cout<<“q             = “<<q<<endl;
 cout<<“n =(p*q)      = “<<n<<endl;
 cout<<“n1=(p-1)*(q-1)= “<<n1<<endl;
 cout<<“e      = “<<e<<endl;
 cout<<“d      = “<<d<<endl<<endl;
 cout<<“Public Key  : { “<<e<<“,”<<n<<” }”<<endl;
 cout<<“Private Key : { “<<d<<“,”<<n<<” }”<<endl;
 cout<<“\nEncrypting myFile.txt …”<<endl;;
 cout<<“\nFinish KeyEnc.txt …”<<endl;
 cout<<“\nDecrypting KeyEnc.txt…”<<endl;
 cout<<“\nFinish KeyDec.txt”<<endl;
//////////////////////////////////// 
 ifstream fin(“myFile.txt”);
 ofstream fout(“KeyEnc.txt”);
 ofstream fout2(“KeyDec.txt”);
 
 char ch;
 int c,m;
 while(!fin.eof())
 {
    fin.get(ch);
if (ch==-1){
    break;
}
  //cout<<ch<<endl;
c=Crypt(ch,e,n);
    fout <<c;; 
  //cout<<c<<endl;
m=Crypt(c,d,n);
    fout2 <<char(m); 
 }
 
 fout.close();
 fout2.close();
 fin.close();
///////////////////////////////////
 getch();
 goto Beg;
}