我在使用这个c++代码时遇到了问题,我试图让它在将字符串转换为ASCII代码后对其进行加密和解密,问题是当它转换为ascii时不会发生加密,我知道我需要单独加密每个ascii代码中的3个数字,然后解密它们,但我不知道该怎么做,我已经尝试了两天,这是我的代码:
#include<iostream>
#include<math.h>
using namespace std;
// find gcd
int gcd(int a, int b) {
int t;
while(1) {
t= a%b;
if(t==0)
return b;
a = b;
b= t;
}
}
int main() {
//2 random prime numbers
double p ,q,track,e;
cout<<"entrer p :";
cin>>p;
if(p)
cout<<"entrer q :";
cin>>q;
double n=p*q;//calculate n
double phi= (p-1)*(q-1);//calculate phi
//public key
//e stands for encrypt
cout<<"entrer e :";
cin>>e;
//for checking that 1 < e < phi(n) and gcd(e, phi(n)) = 1; i.e., e and phi(n) are coprime.
while(e<phi) {
track = gcd(e,phi);
if(track==1)
break;
else
e++;
}
//private key
//d stands for decrypt
//choosing d such that it satisfies d*e = 1 mod phi
double d1=1/e;
string message;
double d=fmod(d1,phi);
char word[32];
int x = 0;
cout << "Please enter the word (maximum 32 characters):\n";
cin >> word;
cout << "The ASCII for this word is:\n";
while (word[x] != '\0') // While the string isn't at the end...
{
cout << int(word[x]); // Transform the char to int
x++;
}
double c = pow(int(word[x]),e); //encrypt the message
double m = pow(c,d);
c=fmod(c,n);
m=fmod(m,n);
cout<<"\n";
cout<<"Original Message = "<<word;
cout<<"\n"<<"p = "<<p;
cout<<"\n"<<"q = "<<q;
cout<<"\n"<<"n = pq = "<<n;
cout<<"\n"<<"phi = "<<phi;
cout<<"\n"<<"e = "<<e;
cout<<"\n"<<"d = "<<d;
cout<<"\n"<<"Encrypted message = "<<c;
cout<<"\n"<<"Decrypted message = "<<m;
return 0;
}
我猜它在这里的作用是尝试一次加密整个ascii代码,但它需要根据它的长度将其分成至少4部分,例如这是我在仅编译此代码时得到的输出: 例如,在这个例子中,hello的ascii是
104101108108111
,但它需要像104 101 108 108 111一样被分割,然后这些数字中的每一个都应该被加密以形成加密消息,我不知道该怎么做
h h f hdhdgddgdg mxndannssndndjqqoqjquqzuz。 ()q 至