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

The following examples show how to use java.math.BigInteger#mod() . 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: RippleExt.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
public static String encodeRipple(byte[] input) {
	BigInteger bi = new BigInteger(1, input);
	StringBuilder s = new StringBuilder();
	while (bi.compareTo(BASE) >= 0) {
		BigInteger mod = bi.mod(BASE);
		s.insert(0, DEFAULT_ALPHABET[mod.intValue()]);
		bi = bi.subtract(mod).divide(BASE);
	}
	s.insert(0, DEFAULT_ALPHABET[bi.intValue()]);
	for (byte anInput : input) {
		if (anInput == 0) {
			s.insert(0, DEFAULT_ALPHABET[0]);
		} else {
			break;
		}
	}
	return s.toString();
}
 
Example 2
Source File: RationalChap14Quiz19.java    From BUPTJava with Apache License 2.0 6 votes vote down vote up
private static BigInteger gcd1(BigInteger n, BigInteger d) {
    BigInteger n1 = n.abs();
    BigInteger n2 = d.abs();
    BigInteger temp;
    if(n1.equals(new BigInteger("0"))){ // 分子为0, 直接返回1即可
        return  new BigInteger("1");
    }
    if(n1.compareTo(n2) <= 0) { // 确保n1 > n2
        temp = n1;
        n1 = n2;
        n2 = temp;
    }

    temp = n1.mod(n2);
    while(!temp.equals(new BigInteger("0"))){
        n1 = n2;
        n2 = temp;
        temp = n1.mod(n2);
    }
    return n2;
}
 
Example 3
Source File: BigIntConstructor.java    From es6draft with MIT License 6 votes vote down vote up
/**
 * BigInt.asIntN ( bits, bigint )
 * 
 * @param cx
 *            the execution context
 * @param thisValue
 *            the function this-value
 * @param bits
 *            the bits value
 * @param bigint
 *            the bigint value
 * @return the result BigInt value
 */
@Function(name = "asIntN", arity = 2)
public static Object asIntN(ExecutionContext cx, Object thisValue, Object bits, Object bigint) {
    /* step 1 */
    long bitsIndex = ToIndex(cx, bits);
    /* step 2 */
    BigInteger bigIntValue = ToBigInt(cx, bigint);
    /* steps 3-4 */
    if (bitsIndex >= Integer.MAX_VALUE) {
        return bigIntValue;
    }
    if (bitsIndex == 0) {
        return BigInteger.ZERO;
    }
    BigInteger m = BigInteger.valueOf(2).pow((int) bitsIndex);
    BigInteger mod = bigIntValue.mod(m);
    if (mod.compareTo(m.shiftRight(1)) >= 0)
        return mod.subtract(m);
    return mod;
}
 
Example 4
Source File: BNField2.java    From protect with MIT License 6 votes vote down vote up
BNField2(BNParams bn, BigInteger re, BigInteger im, boolean reduce) {
	this.bn = bn;
	if (reduce) {
		if (docount && modenable) {
			if (re.signum() < 0 || re.compareTo(bn.p) >= 0) {
				modcount++;
			}
			if (im.signum() < 0 || im.compareTo(bn.p) >= 0) {
				modcount++;
			}
		}
		this.re = re.mod(bn.p);
		this.im = im.mod(bn.p);
	} else {
		this.re = re;
		this.im = im;
	}
}
 
Example 5
Source File: SM2.java    From protools with Apache License 2.0 6 votes vote down vote up
/**
 * 签名
 *
 * @param M       签名信息
 * @param IDA     签名方唯一标识
 * @param keyPair 签名方密钥对
 * @return 签名
 */
public Signature sign(String M, String IDA, SM2KeyPair keyPair) {
    byte[] ZA = ZA(IDA, keyPair.getPublicKey());
    byte[] M_ = join(ZA, M.getBytes());
    BigInteger e = new BigInteger(1, sm3hash(M_));
    // BigInteger k = new BigInteger(
    // "6CB28D99 385C175C 94F94E93 4817663F C176D925 DD72B727 260DBAAE
    // 1FB2F96F".replace(" ", ""), 16);
    BigInteger k;
    BigInteger r;
    do {
        k = random(n);
        ECPoint p1 = G.multiply(k).normalize();
        BigInteger x1 = p1.getXCoord().toBigInteger();
        r = e.add(x1);
        r = r.mod(n);
    } while (r.equals(BigInteger.ZERO) || r.add(k).equals(n));

    BigInteger s = ((keyPair.getPrivateKey().add(BigInteger.ONE).modInverse(n))
            .multiply((k.subtract(r.multiply(keyPair.getPrivateKey()))).mod(n))).mod(n);

    return new Signature(r, s);
}
 
Example 6
Source File: CFrac.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Multiplication (m*a) modulo N, with m often small and <code>a < N</code>.
 * @param m
 * @param a
 * @return (m*a) mod N
 */
private BigInteger mulModN(BigInteger m, BigInteger a) {
	if (m.bitLength()<3) { // 0, 1, 10, 11
		switch (m.intValue()) {
		case 0: return I_0;
		case 1: return a;
		case 2: {
			BigInteger two_a = a.shiftLeft(1); // faster than 2*a or a+a
       		return two_a.compareTo(N)<0 ? two_a : two_a.subtract(N);
		}
		case 3: {
			BigInteger ma_modN = a.shiftLeft(1).add(a); // < 3*N
       		if (ma_modN.compareTo(N)<0) return ma_modN;
       		ma_modN = ma_modN.subtract(N); // < 2*N
       		return ma_modN.compareTo(N)<0 ? ma_modN : ma_modN.subtract(N);
		}
		}
		// adding case 4 does not help because then bitLength() does not fit exactly
	}
	BigInteger product = m.multiply(a);
	return product.compareTo(N)<0 ? product : product.mod(N);
}
 
Example 7
Source File: DSTU4145Signer.java    From ripple-lib-java with ISC License 5 votes vote down vote up
private static BigInteger truncate(BigInteger x, int bitLength)
{
    if (x.bitLength() > bitLength)
    {
        x = x.mod(ONE.shiftLeft(bitLength));
    }
    return x;
}
 
Example 8
Source File: ECKey.java    From nuls-v2 with MIT License 5 votes vote down vote up
/**
 * Returns public key point from the given private key. To convert a byte array into a BigInteger,
 * use {@code new BigInteger(1, bytes);}
 */
public static ECPoint publicPointFromPrivate(BigInteger privKey) {
    /*
     * TODO: FixedPointCombMultiplier currently doesn't support scalars longer than the group order,
     * but that could change in future versions.
     */
    if (privKey.bitLength() > CURVE.getN().bitLength()) {
        privKey = privKey.mod(CURVE.getN());
    }
    return new FixedPointCombMultiplier().multiply(CURVE.getG(), privKey);
}
 
Example 9
Source File: DSASigner.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * generate a signature for the given message using the key we were
 * initialised with. For conventional DSA the message should be a SHA-1
 * hash of the message of interest.
 *
 * @param message the message that will be verified later.
 */
public BigInteger[] generateSignature(
    byte[] message)
{
    DSAParameters   params = key.getParameters();
    BigInteger      q = params.getQ();
    BigInteger      m = calculateE(q, message);
    BigInteger      x = ((DSAPrivateKeyParameters)key).getX();

    if (kCalculator.isDeterministic())
    {
        kCalculator.init(q, x, message);
    }
    else
    {
        kCalculator.init(q, random);
    }

    BigInteger  k = kCalculator.nextK();

    BigInteger  r = params.getG().modPow(k, params.getP()).mod(q);

    k = k.modInverse(q).multiply(m.add(x.multiply(r)));

    BigInteger  s = k.mod(q);

    return new BigInteger[]{ r, s };
}
 
Example 10
Source File: Permutation.java    From raistlic-lib-commons-core with Apache License 2.0 5 votes vote down vote up
@Override
public void fetchPermutation(Object[] elements, BigInteger ordinal) {

  if (elements == null)
    throw new NullPointerException("elements array is null.");

  if (ordinal == null)
    throw new NullPointerException("ordinal number is null.");

  if (ordinal.compareTo(BigInteger.ZERO) < 0)
    throw new IllegalArgumentException(
            "ordinal number out of range: " + ordinal);

  if (ordinal.compareTo(getPermutationCount(elements.length)) >= 0)
    throw new IllegalArgumentException(
            "ordinal number out of range: " +
                    ordinal + " / " + getPermutationCount(elements.length));

  for (int i = 0; i < elements.length - 1; i++) {

    int left = elements.length - i - 1;
    BigInteger leftCount = Factorial.of(left);
    int curr = ordinal.divide(leftCount).intValue();
    ordinal = ordinal.mod(leftCount);
    if (curr > 0) {

      Object temp = elements[curr + i];
      for (int j = curr + i; j > i; j--)
        elements[j] = elements[j - 1];
      elements[i] = temp;
    }
  }
}
 
Example 11
Source File: ECUtil.java    From ECTester with MIT License 5 votes vote down vote up
public static EC_Params fixedRandomKey(EC_Curve curve) {
    byte[] hash = hashCurve(curve);
    BigInteger priv = new BigInteger(1, hash);
    BigInteger order = new BigInteger(1, curve.getParam(EC_Consts.PARAMETER_R)[0]);
    priv = priv.mod(order);
    return new EC_Params(EC_Consts.PARAMETER_S, new byte[][]{toByteArray(priv, curve.getBits())});
}
 
Example 12
Source File: DSA.java    From Bytecoder with Apache License 2.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 13
Source File: SplitBasicOp.java    From jsnark with MIT License 5 votes vote down vote up
@Override
protected void compute(BigInteger[] assignment) {

	BigInteger inVal = assignment[inputs[0].getWireId()];
	if (inVal.compareTo(Config.FIELD_PRIME) > 0) {
		inVal = inVal.mod(Config.FIELD_PRIME);
	}
	for (int i = 0; i < outputs.length; i++) {
		assignment[outputs[i].getWireId()] = inVal.testBit(i) ? BigInteger.ONE
				: BigInteger.ZERO;
	}
}
 
Example 14
Source File: BNPoint.java    From protect with MIT License 5 votes vote down vote up
/**
 * Create a normalized BNCurve point from given affine coordinates and a curve
 *
 * @param E the underlying elliptic curve.
 * @param x the affine x-coordinate (mod p).
 * @param y the affine y-coordinate (mod p).
 */
public BNPoint(BNCurve E, BigInteger x, BigInteger y) {
	this.E = E;
	BigInteger p = E.bn.p; // shorthand
	this.x = x.mod(p);
	this.y = y.mod(p);
	this.z = BNParams._1; // normalized
	if (!E.contains(this)) {
		throw new IllegalArgumentException(pointNotOnCurve);
	}
}
 
Example 15
Source File: BigIntegerSym.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
public static BigInteger jacobiSymbolG(BigInteger a, BigInteger b) {
	BigInteger i1 = a.mod(AbstractIntegerSym.BI_FOUR);
	if (i1.equals(BigInteger.ONE)) {
		return BigInteger.ONE;
	}
	BigInteger i2 = b.mod(AbstractIntegerSym.BI_FOUR);
	if (i2.equals(BigInteger.ONE)) {
		return BigInteger.ONE;
	}
	return AbstractIntegerSym.BI_MINUS_ONE;
}
 
Example 16
Source File: IdHashes.java    From Explorer with Apache License 2.0 5 votes vote down vote up
/**
 * encodes the given string into the base of the dictionary provided in the constructor.
 * 
 * @param value the number to encode.
 * @return the encoded string.
 */
public static String encode(Long value) {

  List<Character> result = new ArrayList<Character>();
  BigInteger base = new BigInteger("" + DICTIONARY.length);
  int exponent = 1;
  BigInteger remaining = new BigInteger(value.toString());
  while (true) {
    BigInteger a = base.pow(exponent); // 16^1 = 16
    BigInteger b = remaining.mod(a); // 119 % 16 = 7 | 112 % 256 = 112
    BigInteger c = base.pow(exponent - 1);
    BigInteger d = b.divide(c);

    // if d > dictionary.length, we have a problem. but BigInteger doesnt have
    // a greater than method :-( hope for the best. theoretically, d is always
    // an index of the dictionary!
    result.add(DICTIONARY[d.intValue()]);
    remaining = remaining.subtract(b); // 119 - 7 = 112 | 112 - 112 = 0

    // finished?
    if (remaining.equals(BigInteger.ZERO)) {
      break;
    }

    exponent++;
  }

  // need to reverse it, since the start of the list contains the least significant values
  StringBuffer sb = new StringBuffer();
  for (int i = result.size() - 1; i >= 0; i--) {
    sb.append(result.get(i));
  }
  return sb.toString();
}
 
Example 17
Source File: DSA.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
private BigInteger generateR(BigInteger p, BigInteger q, BigInteger g,
                     BigInteger k) {
    BigInteger temp = g.modPow(k, p);
    return temp.mod(q);
}
 
Example 18
Source File: RSAKeyPairGenerator.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
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 19
Source File: ECKey.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
private static ECPoint publicPointFromPrivate(BigInteger privKey) {
  if (privKey.bitLength() > CURVE.getN().bitLength()) {
    privKey = privKey.mod(CURVE.getN());
  }
  return new FixedPointCombMultiplier().multiply(CURVE.getG(), privKey);
}
 
Example 20
Source File: DSA.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
private BigInteger generateR(BigInteger p, BigInteger q, BigInteger g,
                     BigInteger k) {
    BigInteger temp = g.modPow(k, p);
    return temp.mod(q);
}