C examples for Data Structure:Encrypt Decrypt
Use the RSA Cipher Method
#include <stdio.h> #include <math.h> #include <string.h> long int i, j, p, q, n, t, flag; long int e[100], d[100], temp[100], msgDecrypt[100], msgEncrypt[100]; char msgOriginal[100]; int prime(long int); int findPrime(long int s); void computeKeys(); long int cd(long int); void encryptMsg(); void decryptMsg(); void main() {/* ww w . j av a 2 s . c o m*/ long int s = 17; p = findPrime(s); printf("First prime number p is: %d \n", p) ; s = 19; q = findPrime(s); printf("\nEnter the Message to be Encrypted, Do Not Include Spaces:\n"); fflush(stdin); scanf("%s",msgOriginal); for (i = 0; msgOriginal[i] != NULL; i++) msgDecrypt[i] = msgOriginal[i]; n = p * q; t = (p - 1) * (q - 1); computeKeys(); printf("\nPossible Values of e and d Are:\n"); for (i = 0; i < j - 1; i++) printf("\n %ld \t %ld", e[i], d[i]); printf("\nSample Public Key: (%ld, %ld)", n, e[i-1]); printf("\nSample Private Key: (%ld, %ld)", n, d[i-1]); encryptMsg(); decryptMsg(); } int findPrime(long int s) { int f, d, tag; f = 2; i = 1; while(i <= s){ tag = 1; for(d = 2 ; d <= f-1 ; d++){ if(f % d == 0) { tag = 0; break ; } } if(tag == 1) { if (i == s) return(f); i++ ; } f++ ; } return(0); } int prime(long int pr) { int i; j=sqrt(pr); for (i = 2; i <= j; i++) { if(pr % i == 0) return 0; } return 1; } void computeKeys() { int k; k = 0; for (i = 2; i < t; i++) { if(t % i == 0) continue; flag = prime(i); if(flag == 1 && i != p && i != q) { e[k] = i; flag = cd(e[k]); if(flag > 0) { d[k] = flag; k++; } if(k == 99) break; } } } long int cd(long int x) { long int k = 1; while(1) { k = k + t; if(k % x == 0) return(k/x); } } void encryptMsg() { long int pt, ct, key = e[0], k, length; i = 0; length = strlen(msgOriginal); while(i != length) { pt = msgDecrypt[i]; pt = pt-96; k = 1; for (j = 0; j < key; j++) { k = k * pt; k = k % n; } temp[i] = k; ct = k + 96; msgEncrypt[i] = ct; i++; } msgEncrypt[i] =- 1; printf("\nThe Encrypted Message:\n"); for (i = 0; msgEncrypt[i] != -1; i++) printf("%c", msgEncrypt[i]); } void decryptMsg() { long int pt, ct, key = d[0], k; i = 0; while(msgEncrypt[i] != -1) { ct = temp[i]; k = 1; for (j = 0; j < key; j++) { k = k * ct; k = k % n; } pt = k + 96; msgDecrypt[i] = pt; i++; } msgDecrypt[i] =- 1; printf("\nThe Decrypted Message:\n"); for (i = 0; msgDecrypt[i] != -1; i++) printf("%c", msgDecrypt[i]); printf("\nThank you. \n "); }