Manikandan Manikandan - 6 days ago 6
Java Question

RSA implementation in Java

I have an assignment on RSA implementation. Just now started working on it.
I need some ideas on random key generation. I'm clear with the theories, but not clear on how to generate those random numbers for public key and private key.
Could I get some help regarding this?

Answer

A Java implementation of RSA could be something similar to this:

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.*;

class Rsa_Implementation
{
 private BigInteger n, d, e;

 public Rsa_Implementation(int bitlen)
{
 SecureRandom r = new SecureRandom();
 BigInteger p = new BigInteger(bitlen / 2, 100, r);
 BigInteger q = new BigInteger(bitlen / 2, 100, r);
 n = p.multiply(q);
 BigInteger m = (p.subtract(BigInteger.ONE))
                .multiply(q.subtract(BigInteger.ONE));
 e = new BigInteger("3");
 while(m.gcd(e).intValue() > 1) e = e.add(new BigInteger("2"));
 d = e.modInverse(m);
 }
public BigInteger encrypt(BigInteger message)
{
 return message.modPow(e, n);
}
public BigInteger decrypt(BigInteger message)
 {
return message.modPow(d, n);
}
}
Comments