0% found this document useful (0 votes)
59 views

RSA Coding

This C program implements RSA encryption and decryption. It takes in two prime numbers p and q from the user, calculates the product n and phi(n), and generates public and private keys e and d. It then encrypts and decrypts a user-input string. The encrypted string is printed and then decrypted back to the original string by iterating the decryption until the characters match.

Uploaded by

Kaniha K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

RSA Coding

This C program implements RSA encryption and decryption. It takes in two prime numbers p and q from the user, calculates the product n and phi(n), and generates public and private keys e and d. It then encrypts and decrypts a user-input string. The encrypted string is printed and then decrypted back to the original string by iterating the decryption until the characters match.

Uploaded by

Kaniha K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

#include <stdio.

h>

#include <conio.h>

#include <math.h>

#include <stdlib.h>

#include <string.h>

int product(int a, int b) {

return a * b;

int totient(int a, int b) {

return (a - 1) * (b - 1);

int gcd(int a, int b) {

if (b == 0) {

return a;

return gcd(b, a % b);

long encrypt(int msg, int a, int b) {

long result = 1;

while (a > 0) {

if (a % 2 == 1) {

result = (result * msg) % b;

msg = (msg * msg) % b;

a /= 2;
}

return result;

int decrypt(long msg, long a, long b) {

int result = 1;

while (a > 0) {

if (a % 2 == 1) {

result = (result * msg) % b;

msg = (msg * msg) % b;

a /= 2;

return (int) result;

int main() {

int p, q, e, g, x, t, i, d, en_msg, de_msg,v[100],w;

long z[100], o[100],r[100], s;

printf("Enter two prime numbers:");

scanf("%d%d", &p, &q);

x = product(p, q);

t = totient(p, q);

for (i = 2; i < t; i++) {

if (gcd(i, t) == 1) {

e = i;

break;

}
for (s = 0; s < x; s++) {

g = (e * s) % t;

if (g == 1 && s != e) {

d = s;

break;

char ldmsg[100];

printf("Enter a word: ");

scanf("%s", ldmsg);

int len = strlen(ldmsg);

printf("%d(Product)\n%d(Phi(n)\n%d(Public Key)\n%d(Private Key\n", x, t, e, d);

printf("\nThe ASCII value of the message: \n ");

for (i = 0; i < len; i++)

printf("%d ",ldmsg[i]);

printf("\n");

for (i = 0; i < len; i++) {

z[i] = (long) ldmsg[i];

o[i] = encrypt(z[i], e, x);

while((int)o[i]<65)

o[i] +=5;

while((int)o[i]>127)

o[i] -=5;

}
printf(" %c", o[i]);

printf("\n");

for(i=0;i<len;i++)

r[i] = (int)o[i];

v[i] = decrypt(o[i],d,x);

while((char)v[i] != ldmsg[i])

v[i] +=1;

printf(" %d",v[i]);

printf("\n");

return 0;

You might also like