Skip to content

Instantly share code, notes, and snippets.

@zikosw
Created November 4, 2014 08:12
Show Gist options
  • Save zikosw/bbd5a8392c7c6a853c1b to your computer and use it in GitHub Desktop.
Save zikosw/bbd5a8392c7c6a853c1b to your computer and use it in GitHub Desktop.
RSA TOC2
import java.math.BigInteger;
import java.security.SecureRandom;
public class RSA {
private static BigInteger n;
private static BigInteger d;
private static BigInteger e;
public static BigInteger randomPrimeBigIntegerRange(int bitLengthFrom, int bitLengthtTo){
SecureRandom rnd = new SecureRandom();
BigInteger two = new BigInteger("2");
BigInteger r;
int i =0;
do{
r = BigInteger.probablePrime(bitLengthtTo,rnd);
}while(r.compareTo(two.pow(bitLengthFrom)) <= 0);
return r;
}
public static BigInteger encrypt(BigInteger message) {
return message.modPow(e, n);
}
public static BigInteger decrypt(BigInteger message) {
return message.modPow(d, n);
}
public static void main(String[] args) {
BigInteger p = randomPrimeBigIntegerRange(31,32);
BigInteger q = randomPrimeBigIntegerRange(31,32);
n = p.multiply(q);
BigInteger phy = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
e = new BigInteger("65537");
while (phy.gcd(e).intValue() > 1) {
e =e.add(new BigInteger("2"));
}
d = e.modInverse(phy);
BigInteger s1 = new BigInteger("55010923");
BigInteger s2 = new BigInteger("55011222");
BigInteger m = s1.multiply(s2);
System.out.println("M is (55010923*55011222):"+m);
BigInteger cipher = encrypt(m);
BigInteger mPrime = decrypt(cipher);
System.out.println("Cipher Message :"+cipher);
System.out.println("Decrypt :"+mPrime);
if(m.equals(mPrime)){
System.out.println("Succeed");
}else{
System.out.println("Fail");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment