⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 rsa1.cpp

📁 c++ encryption using C++
💻 CPP
字号:
# include <iostream.h>
# include <string.h>
# include <fstream.h>
# include <math.h>
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
# define ul unsigned long
ul isPrime(ul n)
{
 ul b=1;
 for(ul i=2;i<n;i++)
  if(n%i==0) { b=0; break; }
 return b;
}
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);
}
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]='\0';
 strrev(ans);
 return(ans);
}
	ul Crypt(int x,int key,int n) // (x^y)%z //Method 2
	{
	 char *B=new char[20];
	 B=ToBin(key);
	 ul ans=1;
	 int c=1;
	 for(ul i=0;i<strlen(B);i++)
	 {
	   c=2*c;
	   ans=(ans*ans)%n;
	   if(B[i]=='1')
	   {
	    c=c+1;
	    ans=(ans*x)%n;
	   }
	 }
	 return(ans);
	}
void main()
{
 clrscr();
 randomize();
  /* K E Y   G E N E R A T I O N */
 ul p,q,n,n1,e,d;
 Beg:    // Reading 2 random prime-numbers from 20 to 50
 p=2+rand()%200;
 q=2+rand()%200;
 if(p==q||!isPrime(p)||!isPrime(q)) goto Beg;
 n = p * q;
n1 = (p-1) * (q-1);
ul 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;
		 ul P1=31,P2,Cypher;
B1:
 Cypher=Crypt(P1,e,n);  //Encrypting using public-key  'e'
 P2=Crypt(Cypher,d,n);//Decrypting using private key 'd'

 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<<"PlainText Before Encryption is : "<<P1<<endl;
cout<<"Cypher is : "<<Cypher<<endl;
cout<<"PlainText After Decryption is : "<<P2<<endl;
getch(); randomize(); clrscr();goto Beg;
 getch();
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -