Data Encryption and Decryption Using RSA Algorithm
Data Encryption and Decryption Using RSA Algorithm
Program:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int isPrime(int n)
{
int i;
for (i = 2; i <= sqrt(n); i++)
{
if (n % i == 0)
{
return 0;
}
}
return 1;
}
/* Encryption
* A function which takes the message, the public key and a number n which is the
* product of p and q. The function encrypts the message using the public key
* and returns the encrypted message.
*/
char *encrypt(char *message, long e, long n)
{
long i;
long len = strlen(message);
char *cipher = (char *)malloc(len * sizeof(char));
for (i = 0; i < len; i++)
{
cipher[i] = pomod(message[i], e, n);
printf("\n%c -> %c", message[i], cipher[i]);
}
return cipher;
}
/* Decryption
* A function which takes the cipher text, the private key and a number n which
* is he product of p and q. The function decrypts the cipher text using the
* private key and returns the decrypted message.
*/
int main()
{
int p, q, lambda_n;
long n, e, d;
char *message;
char *cipher;
printf("\nEnter the value of p: ");
scanf("%d", &p);
printf("\nEnter the value of q: ");
scanf("%d", &q);
if (isPrime(p) && isPrime(q))
{
n = p * q;
lambda_n = totient(p, q);
e = randome(lambda_n);
d = private_key(e, lambda_n);
printf("\nThe value of n is %ld", n);
printf("\nThe value of lambda_n is %d", lambda_n);
printf("\nThe value of e is %ld", e);
printf("\nThe value of d is %ld", d);
printf("\nEnter the message: ");
message = (char *)malloc(sizeof(char) * 100);
scanf("%s", message);
cipher = encrypt(message, e, n);
puts("\nThe encrypted message is: ");
printf("%s", cipher);
message = decrypt(cipher, d, n);
puts("\nThe original message was: ");
printf("%s", message);
}
else
{
printf("\nThe value of p and q should be prime.");
}
return 0;
}
Output:
Enter the value of p: 7
Enter the value of q: 19
The number e should be less than 108
and greater than 1.
Thus, (i * e) % lambda_n = 1, (65 * 5) % 108 = 1
The value of n is 133
The value of lambda_n is 108
The value of e is 5
The value of d is 65
Enter the message: apple
a ->
p -> ?
p -> ?
l -> !
e ->
The encrypted message is:
??!
-> a
? -> p
? -> p
! -> l
-> e
The original message was:
apple