Skip to content

Instantly share code, notes, and snippets.

@yinheli
Created August 3, 2017 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yinheli/ec5590a9c0ee6828e7ca05149f7db1d6 to your computer and use it in GitHub Desktop.
Save yinheli/ec5590a9c0ee6828e7ca05149f7db1d6 to your computer and use it in GitHub Desktop.
import java.math.BigInteger;
import java.util.function.Function;
/**
* @author yinheli
*/
public class RSATest {
private static BigInteger[] commonE = new BigInteger[]{
new BigInteger("3"),
new BigInteger("5"),
new BigInteger("17"),
new BigInteger("257"),
new BigInteger("65537"),
};
public static void main(String[] args) {
// calculate e
BigInteger p = new BigInteger("CF642C412E5D7FC1BAA9AF0CC9EF0B7B", 16);
BigInteger q = new BigInteger("D051E350D4E7D727456E1C75354201E3", 16);
BigInteger dp = new BigInteger("15B66F5FC9E669CEE51DF9CD7FFB1685C8B6FAF84E0BA12B97A743158BB422C201F437260B2A495627ACE33450DAF4DB", 16);
BigInteger dq = new BigInteger("15CF52899A283C4B0BD44967AAC7AE586A4AAACEF2233E4E8C627CE9BA1415953259B4F933D86E02D3614F7F4F886843", 16);
BigInteger e = findE(p, q, dp, dq);
System.out.println(e);
}
public static BigInteger findE(BigInteger p, BigInteger q, BigInteger dp, BigInteger dq) {
BigInteger p1 = p.subtract(BigInteger.ONE);
BigInteger q1 = q.subtract(BigInteger.ONE);
BigInteger n = p.multiply(q);
BigInteger phiN = p1.multiply(q1);
Function<BigInteger, Boolean> isValidE = (e) -> {
if (e.gcd(phiN).equals(BigInteger.ONE)) {
BigInteger d = calculateD(e, phiN);
if (d.multiply(p).equals(dp) && d.multiply(q).equals(dq)) {
return true;
}
}
return false;
};
for (BigInteger e : commonE) {
if (isValidE.apply(e)) {
return e;
}
}
BigInteger e = BigInteger.ONE;
while (e.compareTo(n) < 0) {
e = e.nextProbablePrime();
if (isValidE.apply(e)) {
return e;
}
}
return null;
}
private static BigInteger calculateD(BigInteger e, BigInteger phiN) {
return e.modInverse(phiN);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment