I have made this RSA encryption program but it crashes when it is finished decrypting the line. What is wrong and how can I fix it?
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
bool IsPrime(int p);
int main()
{
int p, q;
int n, phi;
int e, d;
long long int c, dc, m;
long long int newdc, dc2;
string msg1, msg = "Hallo world!";
do
{
cout<<"Enter two large prime numbers (seperated by a space): ";
cin>>p>>q;
}while(!(IsPrime(p) && IsPrime(q)));
cout<<"Computing phi..."<<endl;
phi = (q - 1) * (p - 1);
cout<<"\tphi: "<<phi<<endl;
cout<<"Enter a number ";
cin>>e;
cout<<"Computing d..."<<endl;
d = (e % phi);
cout<<"\td: "<<d<<endl;
cout<<"Computing n..."<<endl;
n = p * q;
cout<<"\tn: "<<n<<endl;
cout<<"Original line:\n";
// Print the ASCII values of the message
for(int i = 0; i < msg.size(); i++)
{
// Show the character it is based on.
cout<<static_cast<int>(msg[i]) << "(" << msg[i] << ") " ;
}
cout<<"\nEncrypted line:\n";
// Show the encrypted bytes
for (int i = 0; i < msg.size(); i++)
{
c = msg[i] ^ e % d;
dc = c ^ d % n;
cout<<dc<<"("<<static_cast<char>(dc)<<") ";
newdc = dc;
msg1[i] = newdc;
}
cout<<"\nDecrypted line:\n";
for(int i = 0; i < msg.size(); i++)
{
m = msg1[i] ^ e % d;
dc2 = m ^ e % n;
cout<<dc2<<"("<<static_cast<char>(dc2)<<") ";
}
cin.get();
}
bool IsPrime(int p)
{
if(p <= 1)
return false;
else if(p == 2)
return true;
else if(p % 2 == 0)
return false;
else
{
bool prime = true;
int divisor = 3;
double num_p = static_cast<double>(p);
int UpperLimitp = static_cast<int>(sqrt(num_p));
while(divisor <= UpperLimitp )
{
if(p % divisor == 0)
prime = false;
divisor += 2;
}
return prime;
}
}
Also in the encrypting and decrypting loop:
what will it do if i change this:
c = msg[i] ^ e % d;
To this:
c = msg[i];
Will it make my encryption brakable?
Also I heard thay RSA is suppose to be a certain ammount of bits eg(1024, 2048, 3082, 4096)... How do I achieve this?