0% found this document useful (0 votes)
112 views2 pages

Rsa PDF

This document contains code for implementing RSA encryption and decryption in Java. It takes in a message as input from the user, encrypts it using the RSA algorithm, and then decrypts the encrypted message back to the original. It generates random prime numbers p and q to calculate the public and private keys, encrypts each character by exponentiating it to the public key modulo n, and decrypts each encrypted character by exponentiating it to the private key modulo n.
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)
112 views2 pages

Rsa PDF

This document contains code for implementing RSA encryption and decryption in Java. It takes in a message as input from the user, encrypts it using the RSA algorithm, and then decrypts the encrypted message back to the original. It generates random prime numbers p and q to calculate the public and private keys, encrypts each character by exponentiating it to the public key modulo n, and decrypts each encrypted character by exponentiating it to the private key modulo n.
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/ 2

RSA

import java.util.*;
import java.io.*;
public class rsa
{
static int gcd(int m,int n)
{
while(n!=0)
{
int r=m%n;
m=n;
n=r;
}
return m;
}public static void main(String args[])
{
int p=0,q=0,n=0,e=0,d=0,phi=0;
int nummes[]=new int[100];
int encrypted[]=new int[100];
int decrypted[]=new int[100];
int i=0,j=0,nofelem=0;
Scanner sc=new Scanner(System.in);
String message ;
System.out.println("Enter the Message tobe encrypted:");
message= sc.nextLine();
System.out.println("Enter value of p and q\n");
p=sc.nextInt();
q=sc.nextInt();
n=p*q;
phi=(p-1)*(q-1);
for(i=2;i<phi;i++)
if(gcd(i,phi)==1) break;
e=i;
for(i=2;i<phi;i++)
if((e*i-1)%phi==0)
break;
d=i;
for(i=0;i<message.length();i++)
{
char c = message.charAt(i);
int a =(int)c;
nummes[i]=c-96;
}
nofelem=message.length();
for(i=0;i<nofelem;i++)
{
encrypted[i]=1;
for(j=0;j<e;j++)
encrypted[i] =(encrypted[i]*nummes[i])%n;
}
System.out.println("\n Encrypted message:");
for(i=0;i<nofelem;i++)
{
System.out.print(encrypted[i]);
System.out.print((char)(encrypted[i]+96));
}
for(i=0;i<nofelem;i++)
{
decrypted[i]=1;
for(j=0;j<d;j++)decrypted[i]=(decrypted[i]*encrypted[i])%n;
}
System.out.println("\n Decrypted message:");
for(i=0;i<nofelem;i++)
System.out.print((char)(decrypted[i]+96));
return;
}
}

You might also like