'incrrect result in pow and gcd function in c++
this is my code for RSA cryptosystem
but I have an error with using the pow function that git an error solution
c = pow(m,e)%n;
and for gcd (greatest common divisor) I'm using #include numeric and algorithm and it does not run but I create function and will be git a solution
this is a full code
#include<iostream>
#include<cmath>
#include<math.h>
#include <algorithm>
#include<numeric>
using namespace std;
int prime(long int pr)
{
int i;
int j = sqrt(pr);
for (i = 2; i <= j; i++)
{
if (pr % i == 0)
return 0;
}
return 1;
}
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
/*int power(int a, int b) {
float r = 1;
while (b != 0) {
r *= a;
--b;
}
return r;
}
*/
int main() {
int flag,w,k;
cout << "Welcome to RSA Project\n\n ";
cout << "Enter First larg prime for p ";
int p,q,phi,n,e,d;
cin >> p;
flag = prime(p);
if (flag == 0)
{
cout << "\nINVALID INPUT\n";
exit(0);
}
cout << "Enter Second larg prime for q ";
cin >> q;
flag = prime(q);
if (flag == 0)
{
cout << "\nINVALID INPUT\n";
exit(0);
}
//compute n= p*q
n = p * q;
// comput phi
phi = (p - 1) * (q - 1);
//chose e or select randomly e must be gcd(e,phi)=1
w = 2;
while (gcd(w, phi) != 1)
{
w++;
}
e = w;
//chose d from random numbers
k = 1;
while (((k * e) % phi) != 1)
{
k++;
}
d = k;
cout << "\nThe public key is : " << "{ " << n << " , " << e << " }";
cout << "\nThe private key is : " << "{ " << n << " , " << d << " }";
cout << "\n*****\n\n p=" << p << "\nq=" << q <<"\nn="<<n<<"\nphi = " << phi << "\ne = " << e << "\nd = " << d << "\n *****";
//Encryption
cout << " \nEnter the message for Encrypt : ";
int m , c;
cin >> m;
//c = pow(m,e)%n; ((( here an error )))
c = pow(m, e);
c = c% n;
cout << "\n message for encrypt : " << m;
cout << " \nmessage after encrypt : " << c;
//Decryption
m = pow(c , d);
m = c% n;
cout << " \nmessage after decrypt : " << m;
}
output : output
it's fully tested but the error with pow function ..
if anyone can help me please ..
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
