Java Code Examples for java.math.BigInteger#bitLength()
The following examples show how to use
java.math.BigInteger#bitLength() .
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: DivisionOverflow.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) { try { BigInteger a = BigInteger.ONE.shiftLeft(2147483646); BigInteger b = BigInteger.ONE.shiftLeft(1568); BigInteger[] qr = a.divideAndRemainder(b); BigInteger q = qr[0]; BigInteger r = qr[1]; if (!r.equals(BigInteger.ZERO)) { throw new RuntimeException("Incorrect signum() of remainder " + r.signum()); } if (q.bitLength() != 2147482079) { throw new RuntimeException("Incorrect bitLength() of quotient " + q.bitLength()); } System.out.println("Division of large values passed without overflow."); } catch (OutOfMemoryError e) { // possible System.err.println("DivisionOverflow skipped: OutOfMemoryError"); System.err.println("Run jtreg with -javaoption:-Xmx8g"); } }
Example 2
Source File: DSAKeyPairGenerator.java From RipplePower with Apache License 2.0 | 6 votes |
private static BigInteger generatePrivateKey(BigInteger q, SecureRandom random) { // B.1.2 Key Pair Generation by Testing Candidates int minWeight = q.bitLength() >>> 2; for (;;) { // TODO Prefer this method? (change test cases that used fixed random) // B.1.1 Key Pair Generation Using Extra Random Bits // BigInteger x = new BigInteger(q.bitLength() + 64, random).mod(q.subtract(ONE)).add(ONE); BigInteger x = BigIntegers.createRandomInRange(ONE, q.subtract(ONE), random); if (WNafUtil.getNafWeight(x) >= minWeight) { return x; } } }
Example 3
Source File: Base64.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
/** * Returns a byte-array representation of a <code>BigInteger</code> without sign bit. * * @param bigInt * <code>BigInteger</code> to be converted * @return a byte array representation of the BigInteger parameter */ static byte[] toIntegerBytes(final BigInteger bigInt) { int bitlen = bigInt.bitLength(); // round bitlen bitlen = ((bitlen + 7) >> 3) << 3; final byte[] bigBytes = bigInt.toByteArray(); if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) { return bigBytes; } // set up params for copying everything but sign bit int startSrc = 0; int len = bigBytes.length; // if bigInt is exactly byte-aligned, just skip signbit in copy if ((bigInt.bitLength() % 8) == 0) { startSrc = 1; len--; } final int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec final byte[] resizedBytes = new byte[bitlen / 8]; System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len); return resizedBytes; }
Example 4
Source File: EcTools.java From guarda-android-wallets with GNU General Public License v3.0 | 6 votes |
/** * Multiply a point with a big integer */ public static Point multiply(Point p, BigInteger k) { BigInteger e = k; BigInteger h = e.multiply(BigInteger.valueOf(3)); Point neg = p.negate(); Point R = p; for (int i = h.bitLength() - 2; i > 0; --i) { R = R.twice(); boolean hBit = h.testBit(i); boolean eBit = e.testBit(i); if (hBit != eBit) { R = R.add(hBit ? p : neg); } } return R; }
Example 5
Source File: MontgomeryLadderMultiplier.java From ripple-lib-java with ISC License | 6 votes |
/** * Montgomery ladder. */ protected ECPoint multiplyPositive(ECPoint p, BigInteger k) { ECPoint[] R = new ECPoint[]{ p.getCurve().getInfinity(), p }; int n = k.bitLength(); int i = n; while (--i >= 0) { int b = k.testBit(i) ? 1 : 0; int bp = 1 - b; R[bp] = R[bp].add(R[b]); R[b] = R[b].twice(); } return R[0]; }
Example 6
Source File: IntegerFunctions.java From RipplePower with Apache License 2.0 | 5 votes |
public static byte[] integerToOctets(BigInteger val) { byte[] valBytes = val.abs().toByteArray(); // check whether the array includes a sign bit if ((val.bitLength() & 7) != 0) { return valBytes; } // get rid of the sign bit (first byte) byte[] tmp = new byte[val.bitLength() >> 3]; System.arraycopy(valBytes, 1, tmp, 0, tmp.length); return tmp; }
Example 7
Source File: FixedPointType.java From etherscan-explorer with GNU General Public License v3.0 | 5 votes |
static BigInteger convert(int mBitSize, int nBitSize, BigInteger m, BigInteger n) { BigInteger mPadded = m.shiftLeft(nBitSize); int nBitLength = n.bitLength(); // find next multiple of 4 int shift = (nBitLength + 3) & ~0x03; return mPadded.or(n.shiftLeft(nBitSize - shift)); }
Example 8
Source File: DSA.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
protected BigInteger generateK(BigInteger q) { // Implementation defined in FIPS 186-4 AppendixB.2.1. SecureRandom random = getSigningRandom(); byte[] kValue = new byte[(q.bitLength() + 7)/8 + 8]; random.nextBytes(kValue); return new BigInteger(1, kValue).mod( q.subtract(BigInteger.ONE)).add(BigInteger.ONE); }
Example 9
Source File: P11RSAKeyParameter.java From xipki with Apache License 2.0 | 5 votes |
private P11RSAKeyParameter(P11CryptService p11CryptService, P11IdentityId identityId, BigInteger modulus, BigInteger publicExponent) { super(true, modulus, publicExponent); Args.notNull(modulus,"modulus"); Args.notNull(publicExponent, "publicExponent"); this.p11CryptService = Args.notNull(p11CryptService, "p11CryptService"); this.identityId = Args.notNull(identityId, "identityId"); this.keysize = modulus.bitLength(); }
Example 10
Source File: DSA.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
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 11
Source File: SupportedDHKeys.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
private static void checkKeyPair(KeyPair kp, int pSize) throws Exception { DHPrivateKey privateKey = (DHPrivateKey)kp.getPrivate(); BigInteger p = privateKey.getParams().getP(); if (p.bitLength() != pSize) { throw new Exception( "Invalid modulus size: " + p.bitLength() + "/" + pSize); } // System.out.println("P(" + pSize + "): " + p.toString()); if (!p.isProbablePrime(128)) { throw new Exception("Good luck, the modulus is composite!"); } DHPublicKey publicKey = (DHPublicKey)kp.getPublic(); p = publicKey.getParams().getP(); if (p.bitLength() != pSize) { throw new Exception( "Invalid modulus size: " + p.bitLength() + "/" + pSize); } BigInteger leftOpen = BigInteger.ONE; BigInteger rightOpen = p.subtract(BigInteger.ONE); BigInteger x = privateKey.getX(); if ((x.compareTo(leftOpen) <= 0) || (x.compareTo(rightOpen) >= 0)) { throw new Exception( "X outside range [2, p - 2]: x: " + x + " p: " + p); } BigInteger y = publicKey.getY(); if ((y.compareTo(leftOpen) <= 0) || (y.compareTo(rightOpen) >= 0)) { throw new Exception( "Y outside range [2, p - 2]: x: " + x + " p: " + p); } }
Example 12
Source File: Base64.java From JDKSourceCode1.8 with MIT License | 5 votes |
/** * Returns a byte-array representation of a <code>{@link BigInteger}<code>. * No sign-bit is output. * * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray * returns eventually longer arrays because of the leading sign-bit. * * @param big <code>BigInteger<code> to be converted * @param bitlen <code>int<code> the desired length in bits of the representation * @return a byte array with <code>bitlen</code> bits of <code>big</code> */ public static final byte[] encode(BigInteger big, int bitlen) { //round bitlen bitlen = ((bitlen + 7) >> 3) << 3; if (bitlen < big.bitLength()) { throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength")); } byte[] bigBytes = big.toByteArray(); if (((big.bitLength() % 8) != 0) && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { return bigBytes; } // some copying needed int startSrc = 0; // no need to skip anything int bigLen = bigBytes.length; //valid length of the string if ((big.bitLength() % 8) == 0) { // correct values startSrc = 1; // skip sign bit bigLen--; // valid length of the string } int startDst = bitlen / 8 - bigLen; //pad with leading nulls byte[] resizedBytes = new byte[bitlen / 8]; System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); return resizedBytes; }
Example 13
Source File: SymmetricRangeTests.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
private static void testAdd() { System.out.println("Testing BigInteger.add"); try { BigInteger actual = MAX_VALUE.add(BigInteger.ONE); throw new RuntimeException("BigInteger.MAX_VALUE.add(BigInteger.ONE).bitLength()=" + actual.bitLength()); } catch (ArithmeticException e) { // expected } }
Example 14
Source File: CurveDB.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
private static void add(String name, String soid, int type, String sfield, String a, String b, String x, String y, String n, int h, Pattern nameSplitPattern) { BigInteger p = bi(sfield); ECField field; if ((type == P) || (type == PD)) { field = new ECFieldFp(p); } else if ((type == B) || (type == BD)) { field = new ECFieldF2m(p.bitLength() - 1, p); } else { throw new RuntimeException("Invalid type: " + type); } EllipticCurve curve = new EllipticCurve(field, bi(a), bi(b)); ECPoint g = new ECPoint(bi(x), bi(y)); NamedCurve params = new NamedCurve(name, soid, curve, g, bi(n), h); if (oidMap.put(soid, params) != null) { throw new RuntimeException("Duplication oid: " + soid); } String[] commonNames = nameSplitPattern.split(name); for (String commonName : commonNames) { if (nameMap.put(commonName.trim(), params) != null) { throw new RuntimeException("Duplication name: " + commonName); } } int len = field.getFieldSize(); if ((type == PD) || (type == BD) || (lengthMap.get(len) == null)) { // add entry if none present for this field size or if // the curve is marked as a default curve. lengthMap.put(len, params); } }
Example 15
Source File: ECKey.java From GreenBits with GNU General Public License v3.0 | 5 votes |
/** * Returns public key point from the given private key. To convert a byte array into a BigInteger, use <tt> * new BigInteger(1, bytes);</tt> */ 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 16
Source File: Signatures.java From guarda-android-wallets with GNU General Public License v3.0 | 5 votes |
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: UnsignedBigInt.java From symja_android_library with GNU General Public License v3.0 | 4 votes |
/** * Sets this to the given BigInteger N. This method must be called before any arithmetic operation. * If a buffer has been passed to the constructor then it should be big enough to represent N. * * @param N */ public void set(BigInteger N) { intLength = (N.bitLength()+31)>>5; // round up if (intLength > 0) { if (intArray == null || intArray.length < intLength) { // allocate new 0-initialized array intArray = new int[intLength]; } else { // clear existing buffer for (int i=intLength-1; i>=0; i--) intArray[i] = 0; // TODO: use arrayCopy() ? } // bytes in big-endian order, i.e. the most significant byte is at index 0 byte[] bytes = N.toByteArray(); // convert byte[] to unsigned int[] //LOG.debug("#bytes = " + bytes.length + ", #ints = " + intLength); int i=0, j=0; for (int bPos=bytes.length-1; bPos>=0; bPos--) { int b = bytes[bPos] & 0xFF; intArray[i] |= b<<(j<<3); if (++j==4) { if (++i == intLength) { // The most significant byte of N.toByteArray() has a sign bit, which is 0 for unsigned integers. // But it may lead to another byte! -> skip that one... //LOG.debug("i has reached maximum value " + i); break; } j = 0; } } } if (DEBUG) { // try { // // compare with slower but safer implementation // int[] intArrayFromNShifts = safeConversion(N); // for (int i=0; i<intLength; i++) { // assertEquals(intArrayFromNShifts[i], intArray[i]); // } // } catch (AssertionError ae) { // LOG.debug("N = " + N.toString(2)); // LOG.debug("UnsignedBigInt = " + this.toBinaryString()); // throw ae; // } } }
Example 18
Source File: ECKey.java From nuls with MIT License | 4 votes |
public static ECPoint publicPointFromPrivate(BigInteger privKey) { if (privKey.bitLength() > CURVE.getN().bitLength()) { privKey = privKey.mod(CURVE.getN()); } return new FixedPointCombMultiplier().multiply(CURVE.getG(), privKey); }
Example 19
Source File: ExactArithTests.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 2 votes |
/** * Check if the value fits in 64 bits (a long). * @param value * @return true if the value fits in 64 bits (including the sign). */ static boolean inLongRange(BigInteger value) { return value.bitLength() <= 63; }
Example 20
Source File: RSACore.java From jdk8u-jdk with GNU General Public License v2.0 | 2 votes |
/** * Return the number of bytes required to store the magnitude byte[] of * this BigInteger. Do not count a 0x00 byte toByteArray() would * prefix for 2's complement form. */ public static int getByteLength(BigInteger b) { int n = b.bitLength(); return (n + 7) >> 3; }