Advertisement
Guest User

rsa2

a guest
Oct 19th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. Homework 01 - Deadline - 11 Oct 2018 23:59
  2. Brute force breaking of RSA
  3. Console application
  4. a) Implement RSA key generation and encryption,
  5. ask for user input (choose primes, plaintext message (number))
  6. b) Given the one side of the key and ciphertext, brute force the message.
  7.  
  8. ---------------------------------------------------------------------------------
  9. RSA implementation
  10.  
  11. Generate public and private keys
  12. Encrypt and decrypt some strings, do it character by character.
  13.  
  14.  
  15. Break cypher using "Brute Force approach", when you know the public key.
  16.  
  17.  
  18.  
  19. using System;
  20. using System.Numerics;
  21.  
  22. namespace RSADemo
  23. {
  24. class Program
  25. {
  26. static void Main(string[] args)
  27. {
  28. Console.WriteLine("Hello RSA!");
  29.  
  30. var p = 7;
  31. var q = 19;
  32. Console.WriteLine($"p: {p} q:{q}");
  33.  
  34. var n = p * q;
  35. var m = (p - 1) * (q - 1);
  36. Console.WriteLine($"n = p*q : {n} m = (p - 1) * (q - 1) :{m}");
  37.  
  38. // find smallest number e (co-prime), where gcd(m,e) == 1
  39. int e = 1;
  40. var gcd = 0;
  41. do
  42. {
  43. e++;
  44. gcd = Gcd(m, e);
  45. Console.WriteLine($"Gcd({m}, {e}) = {gcd}");
  46. } while (gcd != 1);
  47.  
  48. Console.WriteLine($"Co-prime to the m:{m} is e:{e}");
  49.  
  50.  
  51. // Same as finding d,
  52. // which satisfies de=1 + km where k is any integer.
  53. // Rewrite this as d=(1+km)/e
  54.  
  55. int k = 0;
  56.  
  57. do
  58. {
  59. if ((1 + k * m) % e == 0) break;
  60. k++;
  61. } while (true);
  62.  
  63. var d = (1 + k * m) / e;
  64. Console.WriteLine($"d: {d}");
  65.  
  66. Console.WriteLine($"Public key: n:{n} e:{e}");
  67. Console.WriteLine($"Private key: p*q=n : {p}*{q}={n} d:{d}");
  68.  
  69. Console.Write("Plaintext char:");
  70. var plainTextString = Console.ReadLine();
  71. if (plainTextString.Length >= 1)
  72. {
  73. var plainText = (int) plainTextString[0]-65;
  74. Console.WriteLine($"char code is:{plainText}");
  75.  
  76. var cypher = ((int) Math.Pow(plainText, e)) % n;
  77. Console.WriteLine($"Cypher is:{cypher}");
  78.  
  79.  
  80. var decrypttext = BigInteger.ModPow(cypher, d, n);
  81. Console.WriteLine($"Decrypt text is:{decrypttext}");
  82. }
  83.  
  84.  
  85. }
  86.  
  87. // Function to return Greatest Common Divisor of a and b
  88. static int Gcd(int a, int b)
  89. {
  90. if (a == 0)
  91. return b;
  92. return Gcd(b % a, a);
  93. }
  94.  
  95. }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement