Advertisement
GrandtherAzaMarks

RSA

May 25th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. using System;
  2.  
  3. namespace MeyhodsPrepearing
  4. {
  5.     class Program
  6.     {
  7.         static bool Prime(long n)
  8.         {
  9.             for (long i = 2; i <= Math.Sqrt(n); i++)
  10.                 if (n % i == 0) return false;
  11.  
  12.             return true;
  13.         }
  14.         static long GCD(long e, long totient)
  15.         {
  16.             long temp = 0;
  17.             while (totient != 0)
  18.             {
  19.                 temp = e % totient;
  20.                 e = totient;
  21.                 totient = temp;
  22.             }
  23.             return e;
  24.         }
  25.         static long BinPow(long a, long b)
  26.         {
  27.             if (b == 0) return 1;
  28.             else
  29.             {
  30.                 if (b % 2 == 1) return a * BinPow(a, b - 1);
  31.                 else return BinPow(a * a, b / 2);
  32.             }
  33.         }
  34.  
  35.         static void Main(string[] args)
  36.         {
  37.             int p = 0;
  38.             Console.Write("First prime: ");
  39.             do p = Convert.ToInt32(Console.ReadLine()); while (!Prime(p));
  40.  
  41.             int q = 0;
  42.             Console.Write("Second number: ");
  43.             do q = Convert.ToInt32(Console.ReadLine()); while (!Prime(q));
  44.  
  45.             long n = p * q;
  46.             long fi = (p - 1) * (q - 1);
  47.  
  48.             long e = 2;
  49.             Console.Write("E: ");
  50.              
  51.  
  52.             long d = (1 + (2 * fi)) / e;
  53.  
  54.             Console.Write("Message: ");
  55.             long msg1 = Convert.ToInt32(Console.ReadLine());
  56.  
  57.             long c = BinPow(msg1, e) % n;
  58.  
  59.             Console.Write("Encrypted: ");
  60.             Console.WriteLine(c);
  61.  
  62.             long msg2 = BinPow(c, d) % n;
  63.             Console.Write("Original: ");
  64.             Console.WriteLine(msg2);
  65.  
  66.             Console.ReadKey();
  67.         }
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement