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

RSAalgorithm

The document provides a Java program that implements the RSA algorithm for encryption and decryption. It generates public and private keys, allows the user to input a message for encryption, and then decrypts the message back to its original form. The program utilizes BigInteger for mathematical operations and Base64 for encoding the encrypted message.

Uploaded by

csecgirls0203
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

RSAalgorithm

The document provides a Java program that implements the RSA algorithm for encryption and decryption. It generates public and private keys, allows the user to input a message for encryption, and then decrypts the message back to its original form. The program utilizes BigInteger for mathematical operations and Base64 for encoding the encrypted message.

Uploaded by

csecgirls0203
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

EXPERIMENT 8

AIM: Write a Java program to implement RSA Algorithm

import java.math.BigInteger;

import java.security.SecureRandom;

import java.util.Base64;

import java.util.Scanner;

class RSAAlgorithm {

private BigInteger n, e, d;

private int bitLength = 1024;

private SecureRandom random;

public RSAAlgorithm() {

random = new SecureRandom();

BigInteger p = BigInteger.probablePrime(bitLength / 2, random);

BigInteger q = BigInteger.probablePrime(bitLength / 2, random);

n = p.multiply(q);

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

e = new BigInteger("65537"); // Commonly used public exponent

d = e.modInverse(phi);

public String encrypt(String message) {

BigInteger messageBigInt = new BigInteger(1, message.getBytes());

BigInteger encrypted = messageBigInt.modPow(e, n);

return Base64.getEncoder().encodeToString(encrypted.toByteArray());

}
public String decrypt(String encryptedMessage) {

BigInteger encryptedBigInt = new BigInteger(1,


Base64.getDecoder().decode(encryptedMessage));

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

return new String(decrypted.toByteArray());

public void displayKeys() {

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

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

public static void main(String[] args) {

RSAAlgorithm rsa = new RSAAlgorithm();

Scanner scanner = new Scanner(System.in);

rsa.displayKeys();

System.out.print("Enter a message to encrypt: ");

String message = scanner.nextLine();

String encryptedMessage = rsa.encrypt(message);

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

String decryptedMessage = rsa.decrypt(encryptedMessage);

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

scanner.close();
}

OUTPUT:

You might also like