findprivatekey

mail@pastecode.io avatar
unknown
java
3 years ago
1.2 kB
4
Indexable
Never
static BigInteger findPrivateKey(BigInteger e, BigInteger p , BigInteger q)
{   
    BigInteger phi = multiply(subtract(q,BigInteger.ONE),subtract(p,BigInteger.ONE));
    BigInteger inv, u1, u3, v1, v3, t1, t3, q1;
    BigInteger iter;
    BigInteger so0 ;
    so0 = new BigInteger("0");
    /* Step X1. Initialise */
    u1 = BigInteger.ONE;
    u3 = e;
    v1 = BigInteger.valueOf(0);
    v3 = phi;
    /* Remember odd/even iterations */
    iter = BigInteger.ONE;
    /* Step X2. Loop while v3 != 0 */
    while (soNhoHon(so0,v3))
    {
        /* Step X3. Divide and "Subtract" */
        q1 =  u3.divide(v3);
        t3 = u3.mod(v3);
        t1 = add(u1, multiply(q1,v1));
        /* Swap */
        u1 = v1; v1 = t1; u3 = v3; v3 = t3;
        iter = multiply(iter,new BigInteger("-1"));
    }
    /* Make sure u3 = gcd(u,v) == 1 */
    if (!compareEqual(u3, BigInteger.ONE))
        return so0;   /* Error: No inverse exists */
    /* Ensure a positive result */
    if (soNhoHon(iter, BigInteger.valueOf(0)))
        inv = subtract(phi, u1);
    else
        inv = u1;
    System.out.println(inv);
    return inv;
}