Java Code Examples for java.math.BigInteger#modPow()

The following examples show how to use java.math.BigInteger#modPow() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BigIntegerDemoUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenBigIntegers_whenModularCalculation_thenExpectedResult() {
    BigInteger i = new BigInteger("31");
    BigInteger j = new BigInteger("24");
    BigInteger k = new BigInteger("16");

    BigInteger gcd = j.gcd(k);
    BigInteger multiplyAndmod = j.multiply(k)
        .mod(i);
    BigInteger modInverse = j.modInverse(i);
    BigInteger modPow = j.modPow(k, i);

    assertEquals(new BigInteger("8"), gcd);
    assertEquals(new BigInteger("12"), multiplyAndmod);
    assertEquals(new BigInteger("22"), modInverse);
    assertEquals(new BigInteger("7"), modPow);
}
 
Example 2
Source File: CramerShoupParametersGenerator.java    From ripple-lib-java with ISC License 6 votes vote down vote up
static BigInteger selectGenerator(BigInteger p, SecureRandom random)
     {
         BigInteger pMinusTwo = p.subtract(TWO);
         BigInteger g;

/*
          * RFC 2631 2.2.1.2 (and see: Handbook of Applied Cryptography 4.81)
 */
         do
         {
             BigInteger h = BigIntegers.createRandomInRange(TWO, pMinusTwo, random);

             g = h.modPow(TWO, p);
         }
         while (g.equals(ONE));

         return g;
     }
 
Example 3
Source File: RSACore.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * RSA non-CRT private key operations.
 */
private static byte[] priCrypt(byte[] msg, BigInteger n, BigInteger exp)
        throws BadPaddingException {

    BigInteger c = parseMsg(msg, n);
    BlindingRandomPair brp = null;
    BigInteger m;
    if (ENABLE_BLINDING) {
        brp = getBlindingRandomPair(null, exp, n);
        c = c.multiply(brp.u).mod(n);
        m = c.modPow(exp, n);
        m = m.multiply(brp.v).mod(n);
    } else {
        m = c.modPow(exp, n);
    }

    return toByteArray(m, getByteLength(n));
}
 
Example 4
Source File: RSACore.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * RSA non-CRT private key operations.
 */
private static byte[] priCrypt(byte[] msg, BigInteger n, BigInteger exp)
        throws BadPaddingException {

    BigInteger c = parseMsg(msg, n);
    BlindingRandomPair brp = null;
    BigInteger m;
    if (ENABLE_BLINDING) {
        brp = getBlindingRandomPair(null, exp, n);
        c = c.multiply(brp.u).mod(n);
        m = c.modPow(exp, n);
        m = m.multiply(brp.v).mod(n);
    } else {
        m = c.modPow(exp, n);
    }

    return toByteArray(m, getByteLength(n));
}
 
Example 5
Source File: BigIntegerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void modExp(int order1, int order2) {
    int failCount = 0;

    for (int i=0; i<SIZE/10; i++) {
        BigInteger m = fetchNumber(order1).abs();
        while(m.compareTo(BigInteger.ONE) != 1)
            m = fetchNumber(order1).abs();
        BigInteger base = fetchNumber(order2);
        BigInteger exp = fetchNumber(8).abs();

        BigInteger z = base.modPow(exp, m);
        BigInteger w = base.pow(exp.intValue()).mod(m);
        if (!z.equals(w)) {
            System.err.println("z is "+z);
            System.err.println("w is "+w);
            System.err.println("mod is "+m);
            System.err.println("base is "+base);
            System.err.println("exp is "+exp);
            failCount++;
        }
    }
    report("Exponentiation I for " + order1 + " and " +
           order2 + " bits", failCount);
}
 
Example 6
Source File: DSAParameterGenerator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static BigInteger generateG(BigInteger p, BigInteger q) {
    BigInteger h = BigInteger.ONE;
    /* Step 1 */
    BigInteger pMinusOneOverQ = (p.subtract(BigInteger.ONE)).divide(q);
    BigInteger resultG = BigInteger.ONE;
    while (resultG.compareTo(BigInteger.TWO) < 0) {
        /* Step 3 */
        resultG = h.modPow(pMinusOneOverQ, p);
        h = h.add(BigInteger.ONE);
    }
    return resultG;
}
 
Example 7
Source File: BigIntegerArithmetic.java    From chvote-protocol-poc with GNU Affero General Public License v3.0 5 votes vote down vote up
public static BigInteger modExp(BigInteger base, BigInteger exponent, BigInteger modulus) {
    if (gmpLoaded) {
        if (exponent.signum() < 0) {
            return Gmp.modPowSecure(modInverse(base, modulus), exponent.negate(), modulus);
        } else {
            return Gmp.modPowSecure(base, exponent, modulus);
        }
    } else {
        return base.modPow(exponent, modulus);
    }
}
 
Example 8
Source File: ECUtil.java    From ECTester with MIT License 5 votes vote down vote up
private static BigInteger modSqrt(BigInteger a, BigInteger p) {
    BigInteger q = p.subtract(BigInteger.ONE);
    int s = 0;
    while (q.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) {
        q = q.divide(BigInteger.valueOf(2));
        s++;
    }

    BigInteger z = BigInteger.ONE;
    do {
        z = z.add(BigInteger.ONE);
    } while (isResidue(z, p));

    BigInteger m = BigInteger.valueOf(s);
    BigInteger c = z.modPow(q, p);
    BigInteger t = a.modPow(q, p);
    BigInteger rExponent = q.add(BigInteger.ONE).divide(BigInteger.valueOf(2));
    BigInteger r = a.modPow(rExponent, p);

    while (!t.equals(BigInteger.ONE)) {
        int i = 0;
        BigInteger exponent;
        do {
            exponent = BigInteger.valueOf(2).pow(++i);
        } while (!t.modPow(exponent, p).equals(BigInteger.ONE));

        BigInteger twoExponent = m.subtract(BigInteger.valueOf(i + 1));
        BigInteger b = c.modPow(BigInteger.valueOf(2).modPow(twoExponent, p), p);
        m = BigInteger.valueOf(i);
        c = b.modPow(BigInteger.valueOf(2), p);
        t = t.multiply(c).mod(p);
        r = r.multiply(b).mod(p);
    }
    return r;
}
 
Example 9
Source File: SRPHelper.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
public static BigInteger getV(byte[] passwordBytes, TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow algo) {
    BigInteger g = BigInteger.valueOf(algo.g);
    byte[] g_bytes = getBigIntegerBytes(g);
    BigInteger p = new BigInteger(1, algo.p);

    byte[] x_bytes = getX(passwordBytes, algo);
    BigInteger x = new BigInteger(1, x_bytes);
    return g.modPow(x, p);
}
 
Example 10
Source File: SmallPrimes.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Miller-Rabin probabilistic primality test for int type, used in such a way that a result is always guaranteed.
 * <p>
 * It uses the prime numbers as successive base therefore it is guaranteed to be always correct.
 * (see Handbook of applied cryptography by Menezes, table 4.1)
 *
 * @param n number to test: an odd integer &ge; 3
 * @return true if n is prime. false if n is definitely composite.
 */
public static boolean millerRabinPrimeTest(final int n) {
    final int nMinus1 = n - 1;
    final int s = Integer.numberOfTrailingZeros(nMinus1);
    final int r = nMinus1 >> s;
    //r must be odd, it is not checked here
    int t = 1;
    if (n >= 2047) {
        t = 2;
    }
    if (n >= 1373653) {
        t = 3;
    }
    if (n >= 25326001) {
        t = 4;
    } // works up to 3.2 billion, int range stops at 2.7 so we are safe :-)
    BigInteger br = BigInteger.valueOf(r);
    BigInteger bn = BigInteger.valueOf(n);

    for (int i = 0; i < t; i++) {
        BigInteger a = BigInteger.valueOf(SmallPrimes.PRIMES[i]);
        BigInteger bPow = a.modPow(br, bn);
        int y = bPow.intValue();
        if ((1 != y) && (y != nMinus1)) {
            int j = 1;
            while ((j <= s - 1) && (nMinus1 != y)) {
                long square = ((long) y) * y;
                y = (int) (square % n);
                if (1 == y) {
                    return false;
                } // definitely composite
                j++;
            }
            if (nMinus1 != y) {
                return false;
            } // definitely composite
        }
    }
    return true; // definitely prime
}
 
Example 11
Source File: DH1080.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
public String getSharedSecret(String peerPubKey) {
    BigInteger primeInt = new BigInteger(1, decodeB64(PRIME));
    BigInteger peerPubInt = new BigInteger(1, decodeB64(peerPubKey));
    BigInteger shareInt = peerPubInt.modPow(_privateInt, primeInt);
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hashed = md.digest(getBytes(shareInt));
        return encodeB64(hashed);
    } catch (NoSuchAlgorithmException e) {
        logger.debug("Algorithm for DH1080 shared secret hashing not available", e);
    }
    return null;
}
 
Example 12
Source File: Curve.java    From wallet-eos with Apache License 2.0 5 votes vote down vote up
public Point pointFromX(int isOdd, BigInteger x) {
    FieldElement f = this.a.multiply(fromBigInteger(x));
    BigInteger alpha = x.pow(3).add(f.toBigInteger()).add(this.b.toBigInteger()).mod(this.q);
    BigInteger beta = alpha.modPow(this.pOverFour, this.q);
    BigInteger y = beta;
    if (beta.intValue() % 2 == 0 ^ isOdd == 0) {
        y = this.q.subtract(y);
    }
    return new Point(this, new FieldElement(this.q, x), new FieldElement(this.q, y), false);
}
 
Example 13
Source File: DSA.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private BigInteger generateV(BigInteger y, BigInteger p,
         BigInteger q, BigInteger g, BigInteger w, BigInteger r)
         throws SignatureException {

    byte[] s2;
    try {
        s2 = md.digest();
    } catch (RuntimeException re) {
        // Only for RawDSA due to its 20-byte length restriction
        throw new SignatureException(re.getMessage());
    }
    // get the leftmost min(N, outLen) bits of the digest value
    int nBytes = q.bitLength()/8;
    if (nBytes < s2.length) {
        s2 = Arrays.copyOfRange(s2, 0, nBytes);
    }
    BigInteger z = new BigInteger(1, s2);

    BigInteger u1 = z.multiply(w).mod(q);
    BigInteger u2 = (r.multiply(w)).mod(q);

    BigInteger t1 = g.modPow(u1,p);
    BigInteger t2 = y.modPow(u2,p);
    BigInteger t3 = t1.multiply(t2);
    BigInteger t5 = t3.mod(p);
    return t5.mod(q);
}
 
Example 14
Source File: DSAParameterGenerator.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static BigInteger generateG(BigInteger p, BigInteger q) {
    BigInteger h = BigInteger.ONE;
    /* Step 1 */
    BigInteger pMinusOneOverQ = (p.subtract(BigInteger.ONE)).divide(q);
    BigInteger resultG = BigInteger.ONE;
    while (resultG.compareTo(TWO) < 0) {
        /* Step 3 */
        resultG = h.modPow(pMinusOneOverQ, p);
        h = h.add(BigInteger.ONE);
    }
    return resultG;
}
 
Example 15
Source File: Curve.java    From eos4j with GNU General Public License v3.0 5 votes vote down vote up
public Point pointFromX(int isOdd, BigInteger x) {
	FieldElement f = this.a.multiply(fromBigInteger(x));
	BigInteger alpha = x.pow(3).add(f.toBigInteger()).add(this.b.toBigInteger()).mod(this.q);
	BigInteger beta = alpha.modPow(this.pOverFour, this.q);
	BigInteger y = beta;
	if (beta.intValue() % 2 == 0 ^ isOdd == 0) {
		y = this.q.subtract(y);
	}
	return new Point(this, new FieldElement(this.q, x), new FieldElement(this.q, y), false);
}
 
Example 16
Source File: RsaSharing.java    From protect with MIT License 4 votes vote down vote up
public static RsaSharing generateSharing(final int keySizeBits, final int numServers, final int threshold) throws InvalidKeySpecException, NoSuchAlgorithmException {

		final int primeLength = (keySizeBits / 2);
		
		System.out.print("  Generating p...");
		final BigInteger p = Primes.generateSafePrime(primeLength);
		final BigInteger pPrime = Primes.getSophieGermainPrime(p);
		System.out.println(" done.");

		System.out.print("  Generating q...");
		final BigInteger q = Primes.generateSafePrime(primeLength);
		final BigInteger qPrime = Primes.getSophieGermainPrime(q);
		System.out.println(" done.");

		System.out.print("  Computing moduli...");
		final BigInteger m = pPrime.multiply(qPrime);
		final BigInteger n = p.multiply(q);
		System.out.println(" done.");

		// Public exponent (e must be greater than numServers)
		final BigInteger e = BigInteger.valueOf(65537);
		if (e.longValue() <= numServers) {
			throw new IllegalArgumentException("e must be greater than the number of servers!");
		}

		// Create standard RSA Public key pair
		System.out.print("  Creating RSA keypair...");
		final RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(n, e);
		final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		final RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);

		// Create standard RSA Private key
		final BigInteger totient = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
		final BigInteger realD = Exponentiation.modInverse(e, totient);
		final RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(n, realD);
		final RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);
		System.out.println(" done.");

		// Create secret shares of "d"
		System.out.print("  Generating secret shares...");
		final BigInteger d = Exponentiation.modInverse(e, m);

		// Generate random polynomial coefficients for secret sharing of d
		final BigInteger[] coefficients = RandomNumberGenerator.generateRandomArray(threshold, m);

		// Set the secret as the first coefficient
		coefficients[0] = d;

		// Evaluate the polynomial from 1 to numSevers (must not evaluate at zero!)
		final ShamirShare[] shares = new ShamirShare[numServers];
		for (int i = 0; i < numServers; i++) {
			BigInteger xCoord = BigInteger.valueOf(i + 1);
			shares[i] = Polynomials.evaluatePolynomial(coefficients, xCoord, m);
		}
		System.out.println(" done.");

		// Generate public and private verification keys
		System.out.print("  Creating public and private verification keys...");

		// Generate public verification key v as a random square modulo n
		final BigInteger sqrtV = RandomNumberGenerator.generateRandomInteger(n);
		final BigInteger v = sqrtV.modPow(ThresholdSignatures.TWO, n);

		// Generate private verification keys as v^share mod n
		final BigInteger[] verificationKeys = new BigInteger[shares.length];
		for (int i = 0; i < shares.length; i++) {
			verificationKeys[i] = v.modPow(shares[i].getY(), n);
		}
		System.out.println(" done.");

		return new RsaSharing(numServers, threshold, publicKey, privateKey, shares, v, verificationKeys);
	}
 
Example 17
Source File: RSACore.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * RSA private key operations with CRT. Algorithm and variable naming
 * are taken from PKCS#1 v2.1, section 5.1.2.
 */
private static byte[] crtCrypt(byte[] msg, RSAPrivateCrtKey key,
        boolean verify) throws BadPaddingException {
    BigInteger n = key.getModulus();
    BigInteger c0 = parseMsg(msg, n);
    BigInteger c = c0;
    BigInteger p = key.getPrimeP();
    BigInteger q = key.getPrimeQ();
    BigInteger dP = key.getPrimeExponentP();
    BigInteger dQ = key.getPrimeExponentQ();
    BigInteger qInv = key.getCrtCoefficient();
    BigInteger e = key.getPublicExponent();
    BigInteger d = key.getPrivateExponent();

    BlindingRandomPair brp;
    if (ENABLE_BLINDING) {
        brp = getBlindingRandomPair(e, d, n);
        c = c.multiply(brp.u).mod(n);
    }

    // m1 = c ^ dP mod p
    BigInteger m1 = c.modPow(dP, p);
    // m2 = c ^ dQ mod q
    BigInteger m2 = c.modPow(dQ, q);

    // h = (m1 - m2) * qInv mod p
    BigInteger mtmp = m1.subtract(m2);
    if (mtmp.signum() < 0) {
        mtmp = mtmp.add(p);
    }
    BigInteger h = mtmp.multiply(qInv).mod(p);

    // m = m2 + q * h
    BigInteger m = h.multiply(q).add(m2);

    if (ENABLE_BLINDING) {
        m = m.multiply(brp.v).mod(n);
    }
    if (verify && !c0.equals(m.modPow(e, n))) {
        throw new BadPaddingException("RSA private key operation failed");
    }

    return toByteArray(m, getByteLength(n));
}
 
Example 18
Source File: RSACore.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * RSA private key operations with CRT. Algorithm and variable naming
 * are taken from PKCS#1 v2.1, section 5.1.2.
 */
private static byte[] crtCrypt(byte[] msg, RSAPrivateCrtKey key,
        boolean verify) throws BadPaddingException {
    BigInteger n = key.getModulus();
    BigInteger c0 = parseMsg(msg, n);
    BigInteger c = c0;
    BigInteger p = key.getPrimeP();
    BigInteger q = key.getPrimeQ();
    BigInteger dP = key.getPrimeExponentP();
    BigInteger dQ = key.getPrimeExponentQ();
    BigInteger qInv = key.getCrtCoefficient();
    BigInteger e = key.getPublicExponent();
    BigInteger d = key.getPrivateExponent();

    BlindingRandomPair brp;
    if (ENABLE_BLINDING) {
        brp = getBlindingRandomPair(e, d, n);
        c = c.multiply(brp.u).mod(n);
    }

    // m1 = c ^ dP mod p
    BigInteger m1 = c.modPow(dP, p);
    // m2 = c ^ dQ mod q
    BigInteger m2 = c.modPow(dQ, q);

    // h = (m1 - m2) * qInv mod p
    BigInteger mtmp = m1.subtract(m2);
    if (mtmp.signum() < 0) {
        mtmp = mtmp.add(p);
    }
    BigInteger h = mtmp.multiply(qInv).mod(p);

    // m = m2 + q * h
    BigInteger m = h.multiply(q).add(m2);

    if (ENABLE_BLINDING) {
        m = m.multiply(brp.v).mod(n);
    }
    if (verify && !c0.equals(m.modPow(e, n))) {
        throw new BadPaddingException("RSA private key operation failed");
    }

    return toByteArray(m, getByteLength(n));
}
 
Example 19
Source File: DSAKeyPairGenerator.java    From jdk8u-jdk with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Generate the public key component y of the key pair.
 *
 * @param x the private key component.
 *
 * @param p the base parameter.
 */
BigInteger generateY(BigInteger x, BigInteger p, BigInteger g) {
    BigInteger y = g.modPow(x, p);
    return y;
}
 
Example 20
Source File: RSAPublicKey.java    From marauroa with GNU General Public License v2.0 2 votes vote down vote up
/**
 * encodes a BigInteger
 *
 * @param message BigInteger
 * @return encoded BigInteger
 */
public BigInteger encode(BigInteger message) {
	return message.modPow(e, n);
}