Created
November 4, 2014 08:12
-
-
Save zikosw/bbd5a8392c7c6a853c1b to your computer and use it in GitHub Desktop.
RSA TOC2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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