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

The following examples show how to use java.math.BigInteger#modInverse() . These examples are extracted from open source projects. 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
private BigInteger getGenerator(BigInteger q, BigInteger p, BigInteger pMinusOne) {
    log.info("creating a generator");
    BigInteger h = BigInteger.ONE;
    boolean safe = false;
    while (!safe) {
        h = randomGenerator.randomInZq(p);

        safe = modExp(h, TWO, p).compareTo(ONE) != 0
                && modExp(h, q, p).compareTo(ONE) != 0
                && pMinusOne.mod(h).compareTo(BigInteger.ZERO) != 0;

        BigInteger gInv = safe ? h.modInverse(p) : ONE;
        safe = safe && pMinusOne.mod(gInv).compareTo(BigInteger.ZERO) != 0;
    }
    log.info("generator created");
    return modExp(h, TWO, p);
}
 
Example 2
/**
 * Compute the modulus and public exponent from the private CRT key parts and TLV encode them for
 * the card.
 *
 * @param keyType should be 0xB600 for the signature key, 0xB800 for the confidentiality key and
 *                0xA400 for the authentication key.
 * @param p       the first prime.
 * @param q       the second prime.
 * @return the TLV encoded private key.
 */
private byte[] encodeCRTKey(int keyType, String p, String q, String dp1, String dq1, String pq) {
  BigInteger b_p = new BigInteger(1, toByteArray(p));
  BigInteger b_q = new BigInteger(1, toByteArray(q));
  BigInteger b_dp1 = new BigInteger(1, toByteArray(dp1));

  BigInteger e = b_dp1.modInverse(b_p.subtract(BigInteger.ONE));
  BigInteger n = b_p.multiply(b_q);
  byte[] modulus = trimmedBigInteger(n);
  byte[] publicExponent = trimmedBigInteger(e);
  byte[] tag5F48 = TLVDer.createTLVDER(
      0x5F48, mergeByteArrays(publicExponent, toByteArray(p + q + pq + dp1 + dq1), modulus));
  byte[] tag7F48 = TLVDer.createTLVDER(
      0x7F48,
      HexString.mergeByteArrays(createTagLength(0x91, publicExponent.length),
                                createTagLength(0x92, toByteArray(p).length),
                                createTagLength(0x93, toByteArray(q).length),
                                createTagLength(0x94, toByteArray(pq).length),
                                createTagLength(0x95, toByteArray(dp1).length),
                                createTagLength(0x96, toByteArray(dq1).length),
                                createTagLength(0x97, modulus.length)));
  return TLVDer.createTLVDER(0x4D, HexString.mergeByteArrays(
      createTagLength(keyType, 0), tag7F48, tag5F48));
}
 
Example 3
Source Project: protect   File: PaillierKeyGenerator.java    License: MIT License 6 votes vote down vote up
public PaillierKeyPair generate() {
	final SecureRandom random = new SecureRandom();

	final BigInteger p = BigInteger.probablePrime(this.keyLength / 2, random); // random prime
	final BigInteger q = BigInteger.probablePrime(this.keyLength / 2, random); // random prime

	final BigInteger n = p.multiply(q); // p*q
	final BigInteger nSquared = n.multiply(n); // n^2

	final BigInteger pMinusOne = p.subtract(BigInteger.ONE); // p - 1
	final BigInteger qMinusOne = q.subtract(BigInteger.ONE); // q - 1

	final BigInteger lambda = pMinusOne.multiply(qMinusOne); // totient(n)
	final BigInteger g = n.add(BigInteger.ONE); // n + 1
	final BigInteger mu = lambda.modInverse(n); // lambda^-1 % n

	final PaillierPublicKey publicKey = new PaillierPublicKey(n, g, nSquared);
	final PaillierPrivateKey privateKey = new PaillierPrivateKey(lambda, mu, n, nSquared);
	
	return new PaillierKeyPair(publicKey, privateKey);
}
 
Example 4
public static void main(String[] args) throws InterruptedException {
    BigInteger prime = new BigInteger("39402006196394479212279040100143613805079739270465446667946905279627659399113263569398956308152294913554433653942643");
    BigInteger s = new BigInteger("9552729729729327851382626410162104591956625415831952158766936536163093322096473638446154604799898109762512409920799");
    System.out.format("int length: %d, modulus length: %d%n",
        s.bitLength(), prime.bitLength());

    System.out.println("Computing modular inverse ...");
    BigInteger mi = s.modInverse(prime);
    System.out.format("Modular inverse: %s%n", mi);
    check(s, prime, mi);

    BigInteger ns = s.negate();
    BigInteger nmi = ns.modInverse(prime);
    System.out.format("Modular inverse of negation: %s%n", nmi);
    check(ns, prime, nmi);
}
 
Example 5
/**
 * return true if the value r and s represent a DSA signature for
 * the passed in message for standard DSA the message should be a
 * SHA-1 hash of the real message to be verified.
 */
public boolean verifySignature(
    byte[]      message,
    BigInteger  r,
    BigInteger  s)
{
    DSAParameters   params = key.getParameters();
    BigInteger      m = calculateE(params.getQ(), message);
    BigInteger      zero = BigInteger.valueOf(0);

    if (zero.compareTo(r) >= 0 || params.getQ().compareTo(r) <= 0)
    {
        return false;
    }

    if (zero.compareTo(s) >= 0 || params.getQ().compareTo(s) <= 0)
    {
        return false;
    }

    BigInteger  w = s.modInverse(params.getQ());

    BigInteger  u1 = m.multiply(w).mod(params.getQ());
    BigInteger  u2 = r.multiply(w).mod(params.getQ());

    u1 = params.getG().modPow(u1, params.getP());
    u2 = ((DSAPublicKeyParameters)key).getY().modPow(u2, params.getP());

    BigInteger  v = u1.multiply(u2).mod(params.getP()).mod(params.getQ());

    return v.equals(r);
}
 
Example 6
Source Project: protect   File: ShareConversion.java    License: MIT License 5 votes vote down vote up
private static BigInteger computeFactor(final BigInteger[] otherIndices, final int shareholderIndex) {

		final BigInteger i = BigInteger.valueOf(shareholderIndex);

		BigInteger numerator = BigInteger.ONE;
		BigInteger denominator = BigInteger.ONE;

		for (final BigInteger j : otherIndices) {
			numerator = numerator.multiply(i.subtract(j)).mod(r);
			denominator = denominator.multiply(j.negate()).mod(r);
		}

		final BigInteger invDenominator = denominator.modInverse(r);
		return numerator.multiply(invDenominator).mod(r);
	}
 
Example 7
public static void modInv(int order) {
    int failCount = 0, successCount = 0, nonInvCount = 0;

    for (int i=0; i<SIZE; i++) {
        BigInteger x = fetchNumber(order);
        while(x.equals(BigInteger.ZERO))
            x = fetchNumber(order);
        BigInteger m = fetchNumber(order).abs();
        while(m.compareTo(BigInteger.ONE) != 1)
            m = fetchNumber(order).abs();

        try {
            BigInteger inv = x.modInverse(m);
            BigInteger prod = inv.multiply(x).remainder(m);

            if (prod.signum() == -1)
                prod = prod.add(m);

            if (prod.equals(BigInteger.ONE))
                successCount++;
            else
                failCount++;
        } catch(ArithmeticException e) {
            nonInvCount++;
        }
    }
    report("Modular Inverse for " + order + " bits", failCount);
}
 
Example 8
public static void modInv(int order) {
    int failCount = 0, successCount = 0, nonInvCount = 0;

    for (int i=0; i<SIZE; i++) {
        BigInteger x = fetchNumber(order);
        while(x.equals(BigInteger.ZERO))
            x = fetchNumber(order);
        BigInteger m = fetchNumber(order).abs();
        while(m.compareTo(BigInteger.ONE) != 1)
            m = fetchNumber(order).abs();

        try {
            BigInteger inv = x.modInverse(m);
            BigInteger prod = inv.multiply(x).remainder(m);

            if (prod.signum() == -1)
                prod = prod.add(m);

            if (prod.equals(BigInteger.ONE))
                successCount++;
            else
                failCount++;
        } catch(ArithmeticException e) {
            nonInvCount++;
        }
    }
    report("Modular Inverse for " + order + " bits", failCount);
}
 
Example 9
public static void modInv(int order) {
    int failCount = 0, successCount = 0, nonInvCount = 0;

    for (int i=0; i<SIZE; i++) {
        BigInteger x = fetchNumber(order);
        while(x.equals(BigInteger.ZERO))
            x = fetchNumber(order);
        BigInteger m = fetchNumber(order).abs();
        while(m.compareTo(BigInteger.ONE) != 1)
            m = fetchNumber(order).abs();

        try {
            BigInteger inv = x.modInverse(m);
            BigInteger prod = inv.multiply(x).remainder(m);

            if (prod.signum() == -1)
                prod = prod.add(m);

            if (prod.equals(BigInteger.ONE))
                successCount++;
            else
                failCount++;
        } catch(ArithmeticException e) {
            nonInvCount++;
        }
    }
    report("Modular Inverse for " + order + " bits", failCount);
}
 
Example 10
Source Project: incubator-tuweni   File: SECP256K1.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Given the components of a signature and a selector value, recover and return the public key that generated the
 * signature according to the algorithm in SEC1v2 section 4.1.6.
 *
 * <p>
 * The recovery id is an index from 0 to 3 which indicates which of the 4 possible keys is the correct one. Because
 * the key recovery operation yields multiple potential keys, the correct key must either be stored alongside the
 * signature, or you must be willing to try each recovery id in turn until you find one that outputs the key you are
 * expecting.
 *
 * <p>
 * If this method returns null it means recovery was not possible and recovery id should be iterated.
 *
 * <p>
 * Given the above two points, a correct usage of this method is inside a for loop from 0 to 3, and if the output is
 * null OR a key that is not the one you expect, you try again with the next recovery id.
 *
 * @param v Which possible key to recover.
 * @param r The R component of the signature.
 * @param s The S component of the signature.
 * @param messageHash Hash of the data that was signed.
 * @return A ECKey containing only the public part, or {@code null} if recovery wasn't possible.
 */
@Nullable
private static BigInteger recoverFromSignature(int v, BigInteger r, BigInteger s, Bytes32 messageHash) {
  assert (v == 0 || v == 1);
  assert (r.signum() >= 0);
  assert (s.signum() >= 0);
  assert (messageHash != null);

  // Compressed keys require you to know an extra bit of data about the y-coord as there are two possibilities.
  // So it's encoded in the recovery id (v).
  ECPoint R = decompressKey(r, (v & 1) == 1);
  // 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers responsibility).
  if (R == null || !R.multiply(Parameters.CURVE_ORDER).isInfinity()) {
    return null;
  }

  // 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification.
  BigInteger e = messageHash.toUnsignedBigInteger();
  // 1.6. For k from 1 to 2 do the following. (loop is outside this function via iterating v)
  // 1.6.1. Compute a candidate public key as:
  //   Q = mi(r) * (sR - eG)
  //
  // Where mi(x) is the modular multiplicative inverse. We transform this into the following:
  //   Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
  // Where -e is the modular additive inverse of e, that is z such that z + e = 0 (mod n).
  // In the above equation ** is point multiplication and + is point addition (the EC group
  // operator).
  //
  // We can find the additive inverse by subtracting e from zero then taking the mod. For example the additive
  // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8.
  BigInteger eInv = BigInteger.ZERO.subtract(e).mod(Parameters.CURVE_ORDER);
  BigInteger rInv = r.modInverse(Parameters.CURVE_ORDER);
  BigInteger srInv = rInv.multiply(s).mod(Parameters.CURVE_ORDER);
  BigInteger eInvrInv = rInv.multiply(eInv).mod(Parameters.CURVE_ORDER);
  ECPoint q = ECAlgorithms.sumOfTwoMultiplies(Parameters.CURVE.getG(), eInvrInv, R, srInv);

  if (q.isInfinity()) {
    return null;
  }

  byte[] qBytes = q.getEncoded(false);
  // We remove the prefix
  return new BigInteger(1, Arrays.copyOfRange(qBytes, 1, qBytes.length));
}
 
Example 11
public KeyPair generateKeyPair() {
    // accommodate odd key sizes in case anybody wants to use them
    int lp = (keySize + 1) >> 1;
    int lq = keySize - lp;
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    BigInteger e = publicExponent;
    while (true) {
        // generate two random primes of size lp/lq
        BigInteger p = BigInteger.probablePrime(lp, random);
        BigInteger q, n;
        do {
            q = BigInteger.probablePrime(lq, random);
            // convention is for p > q
            if (p.compareTo(q) < 0) {
                BigInteger tmp = p;
                p = q;
                q = tmp;
            }
            // modulus n = p * q
            n = p.multiply(q);
            // even with correctly sized p and q, there is a chance that
            // n will be one bit short. re-generate the smaller prime if so
        } while (n.bitLength() < keySize);

        // phi = (p - 1) * (q - 1) must be relative prime to e
        // otherwise RSA just won't work ;-)
        BigInteger p1 = p.subtract(BigInteger.ONE);
        BigInteger q1 = q.subtract(BigInteger.ONE);
        BigInteger phi = p1.multiply(q1);
        // generate new p and q until they work. typically
        // the first try will succeed when using F4
        if (e.gcd(phi).equals(BigInteger.ONE) == false) {
            continue;
        }

        // private exponent d is the inverse of e mod phi
        BigInteger d = e.modInverse(phi);

        // 1st prime exponent pe = d mod (p - 1)
        BigInteger pe = d.mod(p1);
        // 2nd prime exponent qe = d mod (q - 1)
        BigInteger qe = d.mod(q1);

        // crt coefficient coeff is the inverse of q mod p
        BigInteger coeff = q.modInverse(p);

        try {
            PublicKey publicKey = new RSAPublicKeyImpl(n, e);
            PrivateKey privateKey =
                    new RSAPrivateCrtKeyImpl(n, e, d, p, q, pe, qe, coeff);
            return new KeyPair(publicKey, privateKey);
        } catch (InvalidKeyException exc) {
            // invalid key exception only thrown for keys < 512 bit,
            // will not happen here
            throw new RuntimeException(exc);
        }
    }
}
 
Example 12
private BigInteger generateW(BigInteger p, BigInteger q,
                     BigInteger g, BigInteger s) {
    return s.modInverse(q);
}
 
Example 13
Source Project: ripple-lib-java   File: ECDSASigner.java    License: ISC License 4 votes vote down vote up
/**
 * return true if the value r and s represent a DSA signature for
 * the passed in message (for standard DSA the message should be
 * a SHA-1 hash of the real message to be verified).
 */
public boolean verifySignature(
    byte[]      message,
    BigInteger  r,
    BigInteger  s)
{
    ECDomainParameters ec = key.getParameters();
    BigInteger n = ec.getN();
    BigInteger e = calculateE(n, message);

    // r in the range [1,n-1]
    if (r.compareTo(ONE) < 0 || r.compareTo(n) >= 0)
    {
        return false;
    }

    // s in the range [1,n-1]
    if (s.compareTo(ONE) < 0 || s.compareTo(n) >= 0)
    {
        return false;
    }

    BigInteger c = s.modInverse(n);

    BigInteger u1 = e.multiply(c).mod(n);
    BigInteger u2 = r.multiply(c).mod(n);

    ECPoint G = ec.getG();
    ECPoint Q = ((ECPublicKeyParameters)key).getQ();

    ECPoint point = ECAlgorithms.sumOfTwoMultiplies(G, u1, Q, u2).normalize();

    // components must be bogus.
    if (point.isInfinity())
    {
        return false;
    }

    BigInteger v = point.getAffineXCoord().toBigInteger().mod(n);

    return v.equals(r);
}
 
Example 14
Source Project: ripple-lib-java   File: ECGOST3410Signer.java    License: ISC License 4 votes vote down vote up
/**
 * return true if the value r and s represent a GOST3410 signature for
 * the passed in message (for standard GOST3410 the message should be
 * a GOST3411 hash of the real message to be verified).
 */
public boolean verifySignature(
    byte[]      message,
    BigInteger  r,
    BigInteger  s)
{
    byte[] mRev = new byte[message.length]; // conversion is little-endian
    for (int i = 0; i != mRev.length; i++)
    {
        mRev[i] = message[mRev.length - 1 - i];
    }
    
    BigInteger e = new BigInteger(1, mRev);
    BigInteger n = key.getParameters().getN();

    // r in the range [1,n-1]
    if (r.compareTo(ECConstants.ONE) < 0 || r.compareTo(n) >= 0)
    {
        return false;
    }

    // s in the range [1,n-1]
    if (s.compareTo(ECConstants.ONE) < 0 || s.compareTo(n) >= 0)
    {
        return false;
    }

    BigInteger v = e.modInverse(n);

    BigInteger z1 = s.multiply(v).mod(n);
    BigInteger z2 = (n.subtract(r)).multiply(v).mod(n);

    ECPoint G = key.getParameters().getG(); // P
    ECPoint Q = ((ECPublicKeyParameters)key).getQ();

    ECPoint point = ECAlgorithms.sumOfTwoMultiplies(G, z1, Q, z2).normalize();

    // components must be bogus.
    if (point.isInfinity())
    {
        return false;
    }

    BigInteger R = point.getAffineXCoord().toBigInteger().mod(n);

    return R.equals(r);
}
 
Example 15
Source Project: TencentKona-8   File: DSA.java    License: GNU General Public License v2.0 4 votes vote down vote up
private BigInteger generateW(BigInteger p, BigInteger q,
                     BigInteger g, BigInteger s) {
    return s.modInverse(q);
}
 
Example 16
public KeyPair generateKeyPair() {
    // accommodate odd key sizes in case anybody wants to use them
    int lp = (keySize + 1) >> 1;
    int lq = keySize - lp;
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    BigInteger e = publicExponent;
    while (true) {
        // generate two random primes of size lp/lq
        BigInteger p = BigInteger.probablePrime(lp, random);
        BigInteger q, n;
        do {
            q = BigInteger.probablePrime(lq, random);
            // convention is for p > q
            if (p.compareTo(q) < 0) {
                BigInteger tmp = p;
                p = q;
                q = tmp;
            }
            // modulus n = p * q
            n = p.multiply(q);
            // even with correctly sized p and q, there is a chance that
            // n will be one bit short. re-generate the smaller prime if so
        } while (n.bitLength() < keySize);

        // phi = (p - 1) * (q - 1) must be relative prime to e
        // otherwise RSA just won't work ;-)
        BigInteger p1 = p.subtract(BigInteger.ONE);
        BigInteger q1 = q.subtract(BigInteger.ONE);
        BigInteger phi = p1.multiply(q1);
        // generate new p and q until they work. typically
        // the first try will succeed when using F4
        if (e.gcd(phi).equals(BigInteger.ONE) == false) {
            continue;
        }

        // private exponent d is the inverse of e mod phi
        BigInteger d = e.modInverse(phi);

        // 1st prime exponent pe = d mod (p - 1)
        BigInteger pe = d.mod(p1);
        // 2nd prime exponent qe = d mod (q - 1)
        BigInteger qe = d.mod(q1);

        // crt coefficient coeff is the inverse of q mod p
        BigInteger coeff = q.modInverse(p);

        try {
            PublicKey publicKey = new RSAPublicKeyImpl(n, e);
            PrivateKey privateKey =
                    new RSAPrivateCrtKeyImpl(n, e, d, p, q, pe, qe, coeff);
            return new KeyPair(publicKey, privateKey);
        } catch (InvalidKeyException exc) {
            // invalid key exception only thrown for keys < 512 bit,
            // will not happen here
            throw new RuntimeException(exc);
        }
    }
}
 
Example 17
Source Project: jdk8u-jdk   File: DSA.java    License: GNU General Public License v2.0 4 votes vote down vote up
private BigInteger generateW(BigInteger p, BigInteger q,
                     BigInteger g, BigInteger s) {
    return s.modInverse(q);
}
 
Example 18
private static boolean checkSignature(Point Q, BigInteger n, BigInteger e, BigInteger r, BigInteger s) {
   BigInteger c = s.modInverse(n);

   BigInteger u1 = e.multiply(c).mod(n);
   BigInteger u2 = r.multiply(c).mod(n);

   Point G = Parameters.G;

   Point point = EcTools.sumOfTwoMultiplies(G, u1, Q, u2);

   BigInteger v = point.getX().toBigInteger().mod(n);

   return v.equals(r);
}
 
Example 19
private static boolean checkSignature(Point Q, BigInteger n, BigInteger e, BigInteger r, BigInteger s) {
   BigInteger c = s.modInverse(n);

   BigInteger u1 = e.multiply(c).mod(n);
   BigInteger u2 = r.multiply(c).mod(n);

   Point G = Parameters.G;

   Point point = EcTools.sumOfTwoMultiplies(G, u1, Q, u2);

   BigInteger v = point.getX().toBigInteger().mod(n);

   return v.equals(r);
}
 
Example 20
Source Project: bitshares_wallet   File: Signatures.java    License: MIT License 3 votes vote down vote up
private static boolean checkSignature(Point Q, BigInteger n, BigInteger e, BigInteger r, BigInteger s) {
   BigInteger c = s.modInverse(n);

   BigInteger u1 = e.multiply(c).mod(n);
   BigInteger u2 = r.multiply(c).mod(n);

   Point G = Parameters.G;

   Point point = EcTools.sumOfTwoMultiplies(G, u1, Q, u2);

   BigInteger v = point.getX().toBigInteger().mod(n);

   return v.equals(r);
}