Advertisement
GrandtherAzaMarks

RSA

May 20th, 2018
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.63 KB | None | 0 0
  1. //Program for RSA asymmetric cryptographic algorithm
  2. //for demonstration values are relatively small compared to practical application
  3. #include<stdio.h>
  4. #include <string.h>
  5. #include<stdbool.h>
  6. #include<math.h>
  7.  
  8. bool prime (long n) {
  9.     for (long i = 2; i < sqrt(n); i++) {
  10.         if (n % i == 0) return false;
  11.     }
  12.     return true;
  13. }
  14.  
  15. //to find gcd
  16. long gcd(long a, long h) {
  17.     long temp = 0;
  18.     while (h != 0) {
  19.         temp = a % h;
  20.         a = h;
  21.         h = temp;
  22.     }
  23.     return a;
  24. }
  25.  
  26. //to fast pow
  27. long binPow(long a, long b) {
  28.     if (b == 0) return 1;
  29.     else {
  30.         if (b % 2 == 1) return a * (binPow(a, b - 1));
  31.         else return binPow(a*a, b/2);
  32.     }
  33. }
  34.  
  35. long p = 0;
  36. long q = 0;
  37. long n = 0;
  38. long d = 0;
  39. long f = 0;
  40. long e = 0;
  41. long msg = 0;
  42. long c = 0;
  43. void creatKeyPairs() {
  44.     printf("First prime number: ");
  45.     do scanf(" %ld", &p); while(!prime(p));
  46.     printf("First prime number: ");
  47.     do scanf(" %ld", &q); while(!prime(q));
  48.     n = p*q;
  49.     f = (p-1)*(q-1);
  50.     printf("E: ");
  51.     while (e < f) {
  52.         if (gcd(e, f) == 1) break;
  53.         else scanf("%ld", &e);
  54.     }
  55.     d = (1+(2*f))/e;
  56.     printf("%ld:%ld\n", e, n);
  57. }
  58. void encrypt() {
  59.     printf("Encryption\n");
  60.     printf("e: ");
  61.     scanf("%ld", &e);
  62.     printf("n: ");
  63.     scanf("%ld", &n);
  64.     printf("msg: ");
  65.     scanf("%ld", &msg);
  66.     c = binPow(msg,e)%n;
  67.     printf("Encrypted: %ld", c);
  68. }
  69. void decrypt() {
  70.     printf("Decryption\n");
  71.     creatKeyPairs();
  72.     printf("Give a c: ");
  73.     scanf("%ld", &c);
  74.     msg = binPow(c,d)%n;
  75.     printf("Original msg: %ld", msg);
  76. }
  77. int main()
  78. {
  79.     printf("e = 1 : d = any ");
  80.     int decision = 0;
  81.     scanf("%d", &decision);
  82.     if (decision == 1) encrypt();
  83.     else decrypt();
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement