You are on page 1of 2

Name: Dhir Talreja

Roll No: A115

EXPERIMENT 5

RSA.java:

import java.math.BigInteger;

import java.security.SecureRandom;

public class RSA {

private BigInteger privateKey;

private BigInteger publicKey;

private BigInteger modulus;

public RSA(int bitLength) {

SecureRandom random = new SecureRandom();

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

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

modulus = p.mul ply(q);

BigInteger phi = p.subtract(BigInteger.ONE).mul ply(q.subtract(BigInteger.ONE));

publicKey = BigInteger.valueOf(65537);

privateKey = publicKey.modInverse(phi);

public BigInteger encrypt(BigInteger message) {

return message.modPow(publicKey, modulus);

public BigInteger decrypt(BigInteger encryptedMessage) {


return encryptedMessage.modPow(privateKey, modulus);

public sta c void main(String[] args) {

RSA rsa = new RSA(1024);

String plaintext = "Hello, RSA!";

BigInteger message = new BigInteger(plaintext.getBytes());

BigInteger encryptedMessage = rsa.encrypt(message);

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

BigInteger decryptedMessage = rsa.decrypt(encryptedMessage);

System.out.println("Decrypted message: " + new String(decryptedMessage.toByteArray()));

Code:

You might also like