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

Lab P9

hdfgjhgjhgjtyruty

Uploaded by

bgscse ise
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)
17 views2 pages

Lab P9

hdfgjhgjhgjtyruty

Uploaded by

bgscse ise
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

Lab P9: Develop a program for a simple RSA algorithm to encrypt and decrypt the data.

import java.math.BigInteger;

import java.util.Random;

public class SimpleRSA {

public static void main(String[] args) {

// Step 1: Generate two large prime numbers

Random random = new Random();

BigInteger p = BigInteger.probablePrime(512, random);

BigInteger q = BigInteger.probablePrime(512, random);

// Step 2: Calculate n = p * q and φ(n) = (p-1) * (q-1)

BigInteger n = p.multiply(q);

BigInteger phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));

// Step 3: Choose a public key 'e' such that 1 < e < φ(n) and gcd(e, φ(n)) = 1

BigInteger e = BigInteger.probablePrime(256, random);

while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0) {

e = e.add(BigInteger.ONE);

// Step 4: Calculate the private key 'd' such that (e * d) % φ(n) = 1

BigInteger d = e.modInverse(phi);

// Print public and private keys

System.out.println("Public Key (e, n): (" + e + ", " + n + ")");

System.out.println("Private Key (d, n): (" + d + ", " + n + ")");

// Input data to encrypt

String message = "Hello RSA!";

System.out.println("\nOriginal Message: " + message);

// Convert message to numeric representation (ASCII values concatenated)


byte[] bytes = message.getBytes();

BigInteger plaintext = new BigInteger(bytes);

System.out.println("Numeric Representation: " + plaintext);

// Encrypt the message: ciphertext = (plaintext^e) % n

BigInteger ciphertext = plaintext.modPow(e, n);

System.out.println("Encrypted Message: " + ciphertext);

// Decrypt the message: decrypted = (ciphertext^d) % n

BigInteger decrypted = ciphertext.modPow(d, n);

System.out.println("Decrypted Numeric: " + decrypted);

// Convert back to the original message

String decryptedMessage = new String(decrypted.toByteArray());

System.out.println("Decrypted Message: " + decryptedMessage);

You might also like