Java Code Examples for java.math.BigInteger#modInverse()
The following examples show how to use
java.math.BigInteger#modInverse() .
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: ModInvTime.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
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 2
Source File: Simulation.java From chvote-protocol-poc with GNU Affero General Public License v3.0 | 6 votes |
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 3
Source File: PaillierKeyGenerator.java From protect with MIT License | 6 votes |
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
Source File: GpgCryptoTest.java From OpenPGP-Card with GNU General Public License v3.0 | 6 votes |
/** * 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 5
Source File: BigIntegerTest.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
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 6
Source File: BigIntegerTest.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
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 7
Source File: DSASigner.java From TorrentEngine with GNU General Public License v3.0 | 5 votes |
/** * 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 8
Source File: BigIntegerTest.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
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
Source File: ShareConversion.java From protect with MIT License | 5 votes |
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 10
Source File: DSA.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
private BigInteger generateW(BigInteger p, BigInteger q, BigInteger g, BigInteger s) { return s.modInverse(q); }
Example 11
Source File: DSA.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
private BigInteger generateW(BigInteger p, BigInteger q, BigInteger g, BigInteger s) { return s.modInverse(q); }
Example 12
Source File: RSAKeyPairGenerator.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 4 votes |
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 13
Source File: ECGOST3410Signer.java From ripple-lib-java with ISC License | 4 votes |
/** * 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 14
Source File: ECDSASigner.java From ripple-lib-java with ISC License | 4 votes |
/** * 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 15
Source File: DSA.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
private BigInteger generateW(BigInteger p, BigInteger q, BigInteger g, BigInteger s) { return s.modInverse(q); }
Example 16
Source File: RSAKeyPairGenerator.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
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 File: SECP256K1.java From incubator-tuweni with Apache License 2.0 | 4 votes |
/** * 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 18
Source File: Signatures.java From bitshares_wallet with MIT License | 3 votes |
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
Source File: Signatures.java From AndroidWallet with GNU General Public License v3.0 | 3 votes |
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 File: Signatures.java From Upchain-wallet with GNU Affero General Public License v3.0 | 3 votes |
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); }