附上问题码:注释为我的思路,遇到的问题是加密输入A选项后,不能进行,会停滞,初步测出加密算法的问题,但我解决不了,解密也不能运行解密运算操作,输出明文结果



。大素数为随机生成,素数检测为Miller-Rabin算法。求调好,帮助解决,帮助成长。



#include <iostream>
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<math.h>
#include<cmath>
using namespace std;
typedef unsigned __int64 llong;
/*
一、加密
1、产生2个大的随机数p,q,验证其是否为素数,如果是,结束。不是,继续产生,知道产生2个随机的素数为止。
2、计算n=q*p,m=(p-1)*(q-1);
3、产生一个随机数e,验证是否在m~1间,即m<e<1且(e,m)=1;是则结束,否则,重新产生;
4、计算d,d满足de==1(mod(m));
5、输入明文字符串,根据c=m^e mod(n);
6、输出密文、私钥d和n
二、解密
1、输入私钥d,n以及需要解密的密文c
2、m=c^d mod(n)
3、输出解密后的明文
*/
llong random(llong m,llong n)
{
srand((llong)time(NULL));//拿系统时间作为种子产生随机数
return (llong)(m+rand()%n);//
}
llong order(llong a,llong b)
{
}
int gcd(llong a, llong b)
{
if (a < b)
swap(a, b);
if (b == 0)
return a;
else
return gcd(b, a%b);
}
llong mod_pro(llong x,llong y,llong n)
{
llong ret=0,tmp=x%n;
while(y)
{
if(y&0x1)if((ret+=tmp)>n)ret-=n;
if((tmp<<=1)>n)tmp-=n;
y>>=1;
}
return ret;
}
llong mod(llong a,llong b,llong c)
{
llong ret=1;
while(b)
{
if(b&0x1)ret=mod_pro(ret,a,c);
a=mod_pro(a,a,c);
b>>=1;
}
return ret;
}
llong ran()
{
llong ret=rand();
return ret*rand();
}
bool is_prime(llong n,int t)
{
if(n<2)return false;
if(n==2)return true;
if(!(n&0x1))return false;
llong k=0,m,a,i;
for(m=n-1;!(m&1);m>>=1,k++);
while(t--)
{
a=mod(ran()%(n-2)+2,m,n);
if(a!=1)
{
for(i=0;i<k&&a!=n-1;i++)
a=mod_pro(a,a,n);
if(i>=k)return false;
}
}
return true;
}
void encryption(llong p,llong q)//加密
{
char plain[10000];
char cipher[10000];
int Count =0;
llong n=p*q;
llong m=(p-1)*(q-1);
llong e;
int i=0;
/* while(1)
{
e = random(1,m);
if(gcd(e,m)==1)
break;
}*/
do
{
e = random(1,m);
}while(gcd(e,m)!=1);
int d = 1;
while((e*d)%m!=1)
{
d++;
}
cout<<"Please remember the important number:"<<n<<endl;
cout<<"Please keep your private key:"<<d<<endl;
}
void deciphering()//解密
{
char plain[10000];
char cipher[10000];
int Count =0;
int d,n,i=0;
cout<<"Please input ciphertext:"<<endl;
int t=0;
char z;
while(cin>>z)
{
cipher[t]=z;
t++;
if(getchar()=='\n')
break;
}
cout<<"Please input your private key:"<<endl;
cin>>d;
cout<<"Please input the number n:"<<endl;
cin>>n;
while(cipher[i]!=NULL)
{
char s = (char)pow((llong)cipher[i],d)%n;
cout<<s;
i++;
}
}
int main()
{
char ch;
cout<<"encryption:A\n"<<"deciphering:B"<<endl;
cin>>ch;
switch(ch)
{
llong k,l;
case 'A':
{
while(1)
{
k=random(0,100000000);
if(is_prime(k,3))
break;
}
while(1)
{
l=random(0,100000000);
if(is_prime(l,3))
break;
}
encryption(k,l);
}
case 'B':
deciphering();
}
return 0;
}
/*int main()
{
llong k= random(1,100000000);
if(is_prime(k,3))
cout<<k;
}*/
[培训]科锐逆向工程师培训第53期2025年7月8日开班!