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

The following examples show how to use java.math.BigInteger#shiftRight() . 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: Math_79_MathUtils_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Raise a BigInteger to a BigInteger power.
 * @param k number to raise
 * @param e exponent (must be positive or null)
 * @return k<sup>e</sup>
 * @exception IllegalArgumentException if e is negative
 */
public static BigInteger pow(final BigInteger k, BigInteger e)
    throws IllegalArgumentException {

    if (e.compareTo(BigInteger.ZERO) < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            "cannot raise an integral value to a negative power ({0}^{1})",
            k, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (!BigInteger.ZERO.equals(e)) {
        if (e.testBit(0)) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e.shiftRight(1);
    }

    return result;

}
 
Example 2
Source File: PrivateKeyAccount.java    From WavesJ with MIT License 6 votes vote down vote up
/**
 * Generates a 15-word random seed. This method implements the BIP-39 algorithm with 160 bits of entropy.
 *
 * @return the seed as a String
 */
public static String generateSeed() {
    byte[] bytes = new byte[21];
    new SecureRandom().nextBytes(bytes);
    byte[] rhash = Hash.sha256(bytes, 0, 20);
    bytes[20] = rhash[0];
    BigInteger rand = new BigInteger(bytes);
    BigInteger mask = new BigInteger(new byte[]{0, 0, 7, -1}); // 11 lower bits
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 15; i++) {
        sb.append(i > 0 ? ' ' : "")
                .append(SEED_WORDS[rand.and(mask).intValue()]);
        rand = rand.shiftRight(11);
    }
    return sb.toString();
}
 
Example 3
Source File: DigestMD5Base.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Expands a 7-byte array into an 8-byte array that contains parity bits
 * The binary format of a cryptographic key is:
 *     (B1,B2,...,B7,P1,B8,...B14,P2,B15,...,B49,P7,B50,...,B56,P8)
 * where (B1,B2,...,B56) are the independent bits of a DES key and
 * (PI,P2,...,P8) are reserved for parity bits computed on the preceding
 * seven independent bits and set so that the parity of the octet is odd,
 * i.e., there is an odd number of "1" bits in the octet.
 */
private static byte[] addDesParity(byte[] input, int offset, int len) {
    if (len != 7)
        throw new IllegalArgumentException(
            "Invalid length of DES Key Value:" + len);

    byte[] raw = new byte[7];
    System.arraycopy(input, offset, raw, 0, len);

    byte[] result = new byte[8];
    BigInteger in = new BigInteger(raw);

    // Shift 7 bits each time into a byte
    for (int i=result.length-1; i>=0; i--) {
        result[i] = in.and(MASK).toByteArray()[0];
        result[i] <<= 1;         // make room for parity bit
        in = in.shiftRight(7);
    }
    setParityBit(result);
    return result;
}
 
Example 4
Source File: Math_63_MathUtils_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Raise a BigInteger to a BigInteger power.
 * @param k number to raise
 * @param e exponent (must be positive or null)
 * @return k<sup>e</sup>
 * @exception IllegalArgumentException if e is negative
 */
public static BigInteger pow(final BigInteger k, BigInteger e)
    throws IllegalArgumentException {

    if (e.compareTo(BigInteger.ZERO) < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            LocalizedFormats.POWER_NEGATIVE_PARAMETERS,
            k, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (!BigInteger.ZERO.equals(e)) {
        if (e.testBit(0)) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e.shiftRight(1);
    }

    return result;

}
 
Example 5
Source File: ASN1ObjectIdentifier.java    From ripple-lib-java with ISC License 6 votes vote down vote up
private void writeField(
    ByteArrayOutputStream out,
    BigInteger fieldValue)
{
    int byteCount = (fieldValue.bitLength() + 6) / 7;
    if (byteCount == 0)
    {
        out.write(0);
    }
    else
    {
        BigInteger tmpValue = fieldValue;
        byte[] tmp = new byte[byteCount];
        for (int i = byteCount - 1; i >= 0; i--)
        {
            tmp[i] = (byte)((tmpValue.intValue() & 0x7f) | 0x80);
            tmpValue = tmpValue.shiftRight(7);
        }
        tmp[byteCount - 1] &= 0x7f;
        out.write(tmp, 0, tmp.length);
    }
}
 
Example 6
Source File: IntegerValue.java    From soltix with Apache License 2.0 6 votes vote down vote up
public IntegerValue(BigInteger bigInteger) throws Exception {
    bigValue = bigInteger;

    if (bigInteger.compareTo(BigInteger.ZERO) < 0) {
        throw new Exception("IntegerValue constructor: Type inference is only allowed for positive constants");
    }

    // Count bits needed to represent integer
    int count = 0;
    while (bigInteger.compareTo(BigInteger.ZERO) != 0) {
        bigInteger = bigInteger.shiftRight(1);
        ++count;
    }

    int byteCount = count / 8;
    if (byteCount == 0 || byteCount * 8 != count) ++byteCount;

    type = TypeContainer.getIntegerType(true, byteCount*8);
}
 
Example 7
Source File: Cardumen_0053_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Raise a BigInteger to a BigInteger power.
 * @param k number to raise
 * @param e exponent (must be positive or null)
 * @return k<sup>e</sup>
 * @exception IllegalArgumentException if e is negative
 */
public static BigInteger pow(final BigInteger k, BigInteger e)
    throws IllegalArgumentException {

    if (e.compareTo(BigInteger.ZERO) < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            LocalizedFormats.POWER_NEGATIVE_PARAMETERS,
            k, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (!BigInteger.ZERO.equals(e)) {
        if (e.testBit(0)) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e.shiftRight(1);
    }

    return result;

}
 
Example 8
Source File: ASN1ObjectIdentifier.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
private void writeField(
    ByteArrayOutputStream out,
    BigInteger fieldValue)
{
    int byteCount = (fieldValue.bitLength() + 6) / 7;
    if (byteCount == 0)
    {
        out.write(0);
    }
    else
    {
        BigInteger tmpValue = fieldValue;
        byte[] tmp = new byte[byteCount];
        for (int i = byteCount - 1; i >= 0; i--)
        {
            tmp[i] = (byte)((tmpValue.intValue() & 0x7f) | 0x80);
            tmpValue = tmpValue.shiftRight(7);
        }
        tmp[byteCount - 1] &= 0x7f;
        out.write(tmp, 0, tmp.length);
    }
}
 
Example 9
Source File: MathUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Raise a BigInteger to a BigInteger power.
 * @param k number to raise
 * @param e exponent (must be positive or null)
 * @return k<sup>e</sup>
 * @exception IllegalArgumentException if e is negative
 */
public static BigInteger pow(final BigInteger k, BigInteger e)
    throws IllegalArgumentException {

    if (e.compareTo(BigInteger.ZERO) < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            "cannot raise an integral value to a negative power ({0}^{1})",
            k, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (!BigInteger.ZERO.equals(e)) {
        if (e.testBit(0)) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e.shiftRight(1);
    }

    return result;

}
 
Example 10
Source File: ArithmeticUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Raise a BigInteger to a BigInteger power.
 *
 * @param k Number to raise.
 * @param e Exponent (must be positive or zero).
 * @return k<sup>e</sup>
 * @throws NotPositiveException if {@code e < 0}.
 */
public static BigInteger pow(final BigInteger k, BigInteger e) {
    if (e.compareTo(BigInteger.ZERO) < 0) {
        throw new NotPositiveException(LocalizedFormats.EXPONENT, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (!BigInteger.ZERO.equals(e)) {
        if (e.testBit(0)) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e.shiftRight(1);
    }

    return result;
}
 
Example 11
Source File: MontgomeryMultiplyTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
BigInteger montgomeryMultiply(BigInteger a, BigInteger b, BigInteger N,
        int len, BigInteger n_prime)
        throws Throwable {
    BigInteger T = a.multiply(b);
    BigInteger R = BigInteger.ONE.shiftLeft(len*32);
    BigInteger mask = R.subtract(BigInteger.ONE);
    BigInteger m = (T.and(mask)).multiply(n_prime);
    m = m.and(mask); // i.e. m.mod(R)
    T = T.add(m.multiply(N));
    T = T.shiftRight(len*32); // i.e. T.divide(R)
    if (T.compareTo(N) > 0) {
        T = T.subtract(N);
    }
    return T;
}
 
Example 12
Source File: ECDSASigner.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
protected BigInteger calculateE(BigInteger n, byte[] message)
{
    int log2n = n.bitLength();
    int messageBitLength = message.length * 8;

    BigInteger e = new BigInteger(1, message);
    if (log2n < messageBitLength)
    {
        e = e.shiftRight(messageBitLength - log2n);
    }
    return e;
}
 
Example 13
Source File: BigIntegerOperateBitsTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * shiftRight a negative number;
 * shift distance is multiple of 32;
 * shifted bits are zeroes. 
 */
public void testShiftRightNegZeroesMul32() {
    byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 0, 0, 0, 0, 0, 0, 0, 0};
    int aSign = -1;
    int number = 64;
    byte rBytes[] = {-2, 127, -57, -101, 1, 75, -90, -46, -91};
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger result = aNumber.shiftRight(number);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for(int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", -1, result.signum());
}
 
Example 14
Source File: UInt384.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
/**
 * Return a {@link UInt384} containing the specified value.
 *
 * @param value the value to create a {@link UInt384} for
 * @return a {@link UInt384} containing the specified value
 * @throws IllegalArgumentException if the value is negative or too large to be represented as a UInt384
 */
public static UInt384 valueOf(BigInteger value) {
  checkArgument(value.signum() >= 0, "Argument must be positive");
  checkArgument(value.bitLength() <= 384, "Argument is too large to represent a UInt384");
  if (value.compareTo(BI_MAX_CONSTANT) <= 0) {
    return CONSTANTS[value.intValue()];
  }
  int[] ints = new int[INTS_SIZE];
  for (int i = INTS_SIZE - 1; i >= 0; --i) {
    ints[i] = value.intValue();
    value = value.shiftRight(32);
  }
  return new UInt384(ints);
}
 
Example 15
Source File: Keccak.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private BigInteger rot(BigInteger x, int n) {
    n = n % w;

    BigInteger leftShift = getShiftLeft64(x, n);
    BigInteger rightShift = x.shiftRight(w - n);

    return leftShift.or(rightShift);
}
 
Example 16
Source File: Signatures.java    From bitshares_wallet with MIT License 5 votes vote down vote up
private static BigInteger calculateE(BigInteger n, byte[] message) {
   if (n.bitLength() > message.length * 8) {
      return new BigInteger(1, message);
   } else {
      int messageBitLength = message.length * 8;
      BigInteger trunc = new BigInteger(1, message);

      if (messageBitLength - n.bitLength() > 0) {
         trunc = trunc.shiftRight(messageBitLength - n.bitLength());
      }

      return trunc;
   }
}
 
Example 17
Source File: BitOps.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public static BigInteger shiftRight(BigInteger p, BigInteger p2, NullPointer nullPointer) {
    if (p == null || p2 == null) {
        nullPointer.setNullValue(true);
        return BigInteger.ZERO;
    }
    nullPointer.setNullValue(false);
    int shift = p2.intValue();
    return shift < Long.SIZE * 8 ? p.shiftRight(shift) : BigInteger.ZERO;
}
 
Example 18
Source File: OpBehaviorIntRight.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public BigInteger evaluateBinary(int sizeout, int sizein, BigInteger in1, BigInteger in2) {

	if (in1.signum() < 0 || in2.signum() < 0) {
		throw new AssertException("Expected unsigned in values");
	}
	BigInteger maxShift = BigInteger.valueOf(sizein * 8);
	if (in2.compareTo(maxShift) >= 0) {
		return BigInteger.ZERO;
	}
	return in1.shiftRight(in2.intValue());
}
 
Example 19
Source File: BigIntegerTarget.java    From AVM with MIT License 4 votes vote down vote up
@Callable
public static BigInteger shiftRight(BigInteger testValue) {
    return testValue.shiftRight(5);
}
 
Example 20
Source File: Tnaf.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
/**
 * Computes the <code>&tau;</code>-adic NAF (non-adjacent form) of an
 * element <code>&lambda;</code> of <code><b>Z</b>[&tau;]</code>.
 * @param mu The parameter <code>&mu;</code> of the elliptic curve.
 * @param lambda The element <code>&lambda;</code> of
 * <code><b>Z</b>[&tau;]</code>.
 * @return The <code>&tau;</code>-adic NAF of <code>&lambda;</code>.
 */
public static byte[] tauAdicNaf(byte mu, ZTauElement lambda)
{
    if (!((mu == 1) || (mu == -1)))
    {
        throw new IllegalArgumentException("mu must be 1 or -1");
    }
    
    BigInteger norm = norm(mu, lambda);

    // Ceiling of log2 of the norm 
    int log2Norm = norm.bitLength();

    // If length(TNAF) > 30, then length(TNAF) < log2Norm + 3.52
    int maxLength = log2Norm > 30 ? log2Norm + 4 : 34;

    // The array holding the TNAF
    byte[] u = new byte[maxLength];
    int i = 0;

    // The actual length of the TNAF
    int length = 0;

    BigInteger r0 = lambda.u;
    BigInteger r1 = lambda.v;

    while(!((r0.equals(ECConstants.ZERO)) && (r1.equals(ECConstants.ZERO))))
    {
        // If r0 is odd
        if (r0.testBit(0))
        {
            u[i] = (byte) ECConstants.TWO.subtract((r0.subtract(r1.shiftLeft(1))).mod(ECConstants.FOUR)).intValue();

            // r0 = r0 - u[i]
            if (u[i] == 1)
            {
                r0 = r0.clearBit(0);
            }
            else
            {
                // u[i] == -1
                r0 = r0.add(ECConstants.ONE);
            }
            length = i;
        }
        else
        {
            u[i] = 0;
        }

        BigInteger t = r0;
        BigInteger s = r0.shiftRight(1);
        if (mu == 1)
        {
            r0 = r1.add(s);
        }
        else
        {
            // mu == -1
            r0 = r1.subtract(s);
        }

        r1 = t.shiftRight(1).negate();
        i++;
    }

    length++;

    // Reduce the TNAF array to its actual length
    byte[] tnaf = new byte[length];
    System.arraycopy(u, 0, tnaf, 0, length);
    return tnaf;
}