You are on page 1of 3

‭RSA‬

‭AIM:‬
‭Implementing RSA algorithm .‬
‭Code :‬
1‭ .‬ ‭#include <iostream>‬
‭2.‬ ‭#include <math.h>‬
‭3.‬ ‭using namespace std;‬
‭4.‬ ‭int gcd(int a, int b)‬
‭5.‬ ‭{‬
‭6.‬ ‭int t;‬
‭7.‬ ‭while (1)‬
‭8.‬ ‭{‬
‭9.‬ ‭t = a % b;‬
‭10.‬ ‭if (t == 0)‬
‭11.‬ ‭return b;‬
‭12.‬ ‭a = b;‬
‭13.‬ ‭b = t;‬
‭14.‬ ‭}‬
‭15.‬‭}‬
‭16.‬‭int main()‬
‭17.‬‭{‬
‭18.‬ ‭// random primary numbers p and q‬
‭19.‬ ‭double p;‬
‭20.‬ ‭cout << "Enter the value of P : ";‬
‭21.‬ ‭cin >> p;‬
‭22.‬ ‭double q;‬
‭23.‬ ‭cout << "Enter the value of q : ";‬
‭24.‬ ‭cin >> q;‬
‭25.‬ ‭double n = p * q;‬
‭26.‬ ‭double track;‬
‭27.‬ ‭double phi = (p - 1) * (q - 1);‬
‭28.‬ ‭// e stands for encrypt‬
‭29.‬ ‭double e = 2;‬
‭30.‬ ‭while (e < phi)‬
‭31.‬ ‭{‬
‭32.‬ ‭track = gcd(e, phi);‬
‭33.‬ ‭if (track == 1)‬
‭34.‬ ‭{‬
‭35.‬ ‭break;‬
3‭ 6.‬ }‭ ‬
‭37.‬ ‭else‬
‭38.‬ ‭{‬
‭39.‬ ‭e++;‬
‭40.‬ ‭}‬
‭41.‬ }‭ ‬
‭42.‬ ‭// d stands for decrypt‬
‭43.‬ ‭// choosing d such that it satisfies d*e = 1 mod phi‬
‭44.‬ ‭double d1 = 1 / e;‬
‭45.‬ ‭double d = fmod(d1, phi);‬
‭46.‬ ‭double message;‬
‭47.‬ ‭cout << "Enter the message : ";‬
‭48.‬ ‭cin >> message;‬
‭49.‬ ‭// encrypt the message‬
‭50.‬ ‭double c = pow(message, e);‬
‭51.‬ ‭double m = pow(c, d);‬
‭52.‬ ‭c = fmod(c, n);‬
‭53.‬ ‭m = fmod(m, n);‬
‭54.‬ ‭cout << "Original Message = " << message;‬
‭55.‬ ‭cout << "\n"‬
‭56.‬ ‭<< "p = " << p;‬
‭57.‬ ‭cout << "\n"‬
‭58.‬ ‭<< "q = " << q;‬
‭59.‬ ‭cout << "\n"‬
‭60.‬ ‭<< "n = pq = " << n;‬
‭61.‬ ‭cout << "\n"‬
‭62.‬ ‭<< "phi = " << phi << endl;‬
‭63.‬ ‭cout << endl;‬
‭64.‬ ‭cout << "*******e<phi(n) , GCD(e,phi(n)) *****:";‬
‭65.‬ ‭cout << "\n"‬
‭66.‬ ‭<< "e = " << e << endl;‬
‭67.‬ ‭cout << "**** e.d mod phi(n) ****";‬
‭68.‬ ‭cout << "\n"‬
‭69.‬ ‭<< "d = " << d;‬
‭70.‬ ‭cout << endl;‬
‭71.‬ ‭cout << "\n"‬
‭72.‬ ‭<< "Encrypted message = " << c;‬
‭73.‬ ‭cout << "\n"‬
‭74.‬ ‭<< "Decrypted message = " << m;‬
‭75.‬ ‭return 0;‬
‭76.‬‭}‬

‭OUTPUT :‬

You might also like