Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Program for RSA asymmetric cryptographic algorithm
- //for demonstration values are relatively small compared to practical application
- #include<stdio.h>
- #include <string.h>
- #include<stdbool.h>
- #include<math.h>
- bool prime (long n) {
- for (long i = 2; i < sqrt(n); i++) {
- if (n % i == 0) return false;
- }
- return true;
- }
- //to find gcd
- long gcd(long a, long h) {
- long temp = 0;
- while (h != 0) {
- temp = a % h;
- a = h;
- h = temp;
- }
- return a;
- }
- //to fast pow
- long binPow(long a, long b) {
- if (b == 0) return 1;
- else {
- if (b % 2 == 1) return a * (binPow(a, b - 1));
- else return binPow(a*a, b/2);
- }
- }
- long p = 0;
- long q = 0;
- long n = 0;
- long d = 0;
- long f = 0;
- long e = 0;
- long msg = 0;
- long c = 0;
- void creatKeyPairs() {
- printf("First prime number: ");
- do scanf(" %ld", &p); while(!prime(p));
- printf("First prime number: ");
- do scanf(" %ld", &q); while(!prime(q));
- n = p*q;
- f = (p-1)*(q-1);
- printf("E: ");
- while (e < f) {
- if (gcd(e, f) == 1) break;
- else scanf("%ld", &e);
- }
- d = (1+(2*f))/e;
- printf("%ld:%ld\n", e, n);
- }
- void encrypt() {
- printf("Encryption\n");
- printf("e: ");
- scanf("%ld", &e);
- printf("n: ");
- scanf("%ld", &n);
- printf("msg: ");
- scanf("%ld", &msg);
- c = binPow(msg,e)%n;
- printf("Encrypted: %ld", c);
- }
- void decrypt() {
- printf("Decryption\n");
- creatKeyPairs();
- printf("Give a c: ");
- scanf("%ld", &c);
- msg = binPow(c,d)%n;
- printf("Original msg: %ld", msg);
- }
- int main()
- {
- printf("e = 1 : d = any ");
- int decision = 0;
- scanf("%d", &decision);
- if (decision == 1) encrypt();
- else decrypt();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement