List of usage examples for java.math BigInteger multiply
BigInteger multiply(long v)
From source file:com.abiquo.api.services.appslibrary.event.TemplateFactory.java
/** * Gets the disk capacity on bytes.//from ww w . j a va 2 s . c o m * * @param capacity, numeric value * @param alloctionUnit, bytes by default but can be Kb, Mb, Gb or Tb. * @return capacity on bytes **/ private static BigInteger getBytes(final String capacity, final String allocationUnits) { BigInteger capa = new BigInteger(capacity); if (allocationUnits == null) { return capa; } if ("byte".equalsIgnoreCase(allocationUnits) || "bytes".equalsIgnoreCase(allocationUnits)) { return capa; } BigInteger factor = new BigInteger("2"); if ("byte * 2^10".equals(allocationUnits) || "KB".equalsIgnoreCase(allocationUnits) || "KILOBYTE".equalsIgnoreCase(allocationUnits) || "KILOBYTES".equalsIgnoreCase(allocationUnits)) // kb { factor = factor.pow(10); } else if ("byte * 2^20".equals(allocationUnits) || "MB".equalsIgnoreCase(allocationUnits) || "MEGABYTE".equalsIgnoreCase(allocationUnits) || "MEGABYTES".equalsIgnoreCase(allocationUnits)) // mb { factor = factor.pow(20); } else if ("byte * 2^30".equals(allocationUnits) || "GB".equalsIgnoreCase(allocationUnits) || "GIGABYTE".equalsIgnoreCase(allocationUnits) || "GIGABYTES".equalsIgnoreCase(allocationUnits)) // gb { factor = factor.pow(30); } else if ("byte * 2^40".equals(allocationUnits) || "TB".equalsIgnoreCase(allocationUnits) || "TERABYTE".equalsIgnoreCase(allocationUnits) || "TERABYTES".equalsIgnoreCase(allocationUnits)) // tb { factor = factor.pow(40); } else { final String msg = "Unknow disk capacityAllocationUnits factor [" + allocationUnits + "]"; throw new RuntimeException(msg); } return capa.multiply(factor); }
From source file:org.apache.flink.graph.library.clustering.directed.TriadicCensus.java
@Override public Result getResult() { BigInteger one = BigInteger.ONE; BigInteger two = BigInteger.valueOf(2); BigInteger three = BigInteger.valueOf(3); BigInteger six = BigInteger.valueOf(6); BigInteger vertexCount = BigInteger.valueOf((Long) vertexDegreesHelper.getAccumulator(env, "vc")); BigInteger unidirectionalEdgeCount = BigInteger .valueOf((Long) vertexDegreesHelper.getAccumulator(env, "uec") / 2); BigInteger bidirectionalEdgeCount = BigInteger .valueOf((Long) vertexDegreesHelper.getAccumulator(env, "bec") / 2); BigInteger triplet021dCount = BigInteger.valueOf((Long) vertexDegreesHelper.getAccumulator(env, "021d")); BigInteger triplet021uCount = BigInteger.valueOf((Long) vertexDegreesHelper.getAccumulator(env, "021u")); BigInteger triplet021cCount = BigInteger.valueOf((Long) vertexDegreesHelper.getAccumulator(env, "021c")); BigInteger triplet111dCount = BigInteger.valueOf((Long) vertexDegreesHelper.getAccumulator(env, "111d")); BigInteger triplet111uCount = BigInteger.valueOf((Long) vertexDegreesHelper.getAccumulator(env, "111u")); BigInteger triplet201Count = BigInteger.valueOf((Long) vertexDegreesHelper.getAccumulator(env, "201")); // triads with three connecting edges = closed triplet = triangle BigInteger triangle030tCount = BigInteger.valueOf((Long) triangleListingHelper.getAccumulator(env, "030t")); BigInteger triangle030cCount = BigInteger.valueOf((Long) triangleListingHelper.getAccumulator(env, "030c")); BigInteger triangle120dCount = BigInteger.valueOf((Long) triangleListingHelper.getAccumulator(env, "120d")); BigInteger triangle120uCount = BigInteger.valueOf((Long) triangleListingHelper.getAccumulator(env, "120u")); BigInteger triangle120cCount = BigInteger.valueOf((Long) triangleListingHelper.getAccumulator(env, "120c")); BigInteger triangle210Count = BigInteger.valueOf((Long) triangleListingHelper.getAccumulator(env, "210")); BigInteger triangle300Count = BigInteger.valueOf((Long) triangleListingHelper.getAccumulator(env, "300")); // triads with two connecting edges = open triplet; // each triangle deducts the count of three triplets triplet201Count = triplet201Count.subtract(triangle300Count.multiply(three)); triplet201Count = triplet201Count.subtract(triangle210Count); triplet111dCount = triplet111dCount.subtract(triangle210Count); triplet111uCount = triplet111uCount.subtract(triangle210Count); triplet111dCount = triplet111dCount.subtract(triangle120cCount); triplet111uCount = triplet111uCount.subtract(triangle120cCount); triplet021cCount = triplet021cCount.subtract(triangle120cCount); triplet111uCount = triplet111uCount.subtract(triangle120uCount.multiply(two)); triplet021uCount = triplet021uCount.subtract(triangle120uCount); triplet111dCount = triplet111dCount.subtract(triangle120dCount.multiply(two)); triplet021dCount = triplet021dCount.subtract(triangle120dCount); triplet021cCount = triplet021cCount.subtract(triangle030cCount.multiply(three)); triplet021cCount = triplet021cCount.subtract(triangle030tCount); triplet021uCount = triplet021uCount.subtract(triangle030tCount); triplet021dCount = triplet021dCount.subtract(triangle030tCount); // triads with one connecting edge; each edge pairs with `vertex count - 2` vertices; // each triangle deducts from three and each open triplet from two edges BigInteger edge102 = bidirectionalEdgeCount.multiply(vertexCount.subtract(two)).subtract(triplet111dCount) .subtract(triplet111uCount).subtract(triplet201Count.multiply(two)).subtract(triangle120dCount) .subtract(triangle120uCount).subtract(triangle120cCount).subtract(triangle210Count.multiply(two)) .subtract(triangle300Count.multiply(three)); BigInteger edge012 = unidirectionalEdgeCount.multiply(vertexCount.subtract(two)) .subtract(triplet021dCount.multiply(two)).subtract(triplet021uCount.multiply(two)) .subtract(triplet021cCount.multiply(two)).subtract(triplet111dCount).subtract(triplet111uCount) .subtract(triangle030tCount.multiply(three)).subtract(triangle030cCount.multiply(three)) .subtract(triangle120dCount.multiply(two)).subtract(triangle120uCount.multiply(two)) .subtract(triangle120cCount.multiply(two)).subtract(triangle210Count); // triads with zero connecting edges; // (vertex count choose 3) minus earlier counts BigInteger triad003 = vertexCount.multiply(vertexCount.subtract(one)).multiply(vertexCount.subtract(two)) .divide(six).subtract(edge012).subtract(edge102).subtract(triplet021dCount) .subtract(triplet021uCount).subtract(triplet021cCount).subtract(triplet111dCount) .subtract(triplet111uCount).subtract(triangle030tCount).subtract(triangle030cCount) .subtract(triplet201Count).subtract(triangle120dCount).subtract(triangle120uCount) .subtract(triangle120cCount).subtract(triangle210Count).subtract(triangle300Count); return new Result(triad003, edge012, edge102, triplet021dCount, triplet021uCount, triplet021cCount, triplet111dCount, triplet111uCount, triangle030tCount, triangle030cCount, triplet201Count, triangle120dCount, triangle120uCount, triangle120cCount, triangle210Count, triangle300Count); }
From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java
/** * @param originalMessage/* w ww .java 2 s . c o m*/ * original message to be changed * @param si * factor * @return Prepared message as byte array */ private byte[] prepareMsg(final BigInteger originalMessage, final BigInteger si) { byte[] msg; BigInteger tmp; // encrypt: si^e mod n tmp = si.modPow(this.pubKey.getPublicExponent(), this.pubKey.getModulus()); // blind: c0*(si^e) mod n // or: m*si mod n (in case of plaintext m_Oracle) tmp = originalMessage.multiply(tmp); tmp = tmp.mod(this.pubKey.getModulus()); // get bytes msg = correctSize(tmp.toByteArray(), this.blockSize, true); return msg; }
From source file:org.micromanager.plugins.magellan.autofocus.CrossCorrelationAutofocus.java
/** * Called by acquisitions at then end of time point * @param timeIndex //from ww w .j a v a2s. c o m */ public void run(int timeIndex) throws Exception { Log.log("________", true); Log.log("Autofocus for acq " + acq_.getName() + " Time point " + timeIndex, true); if (timeIndex == 0) { //get initial position try { currentPosition_ = initialPosition_; previousPosition_ = initialPosition_; } catch (Exception e) { Log.log("Couldn't get autofocus Z drive initial position", true); } //figure out which resolution level will be used for xCorr MultiResMultipageTiffStorage storage = acq_.getStorage(); //do these calulations with BigIntegers to prevent overflow and Nan values BigInteger tileWidth = new BigInteger(storage.getTileWidth() + ""); BigInteger tileHeight = new BigInteger(storage.getTileHeight() + ""); BigInteger numCols = new BigInteger(acq_.getNumColumns() + ""); BigInteger numRows = new BigInteger(acq_.getNumRows() + ""); //figure out how much downsampling needed to run autofocus in a reasonable amount of time //factor of two is for z padding BigDecimal numPix2D = new BigDecimal( tileWidth.multiply(numCols).multiply(tileHeight).multiply(numRows)); BigDecimal numXCorrSlices = new BigDecimal((acq_.getNumSlices()) + ""); double dsFactor = //ratio of number of voxels to voxel target Math.sqrt(numPix2D.multiply(numXCorrSlices) .divide(new BigDecimal((double) NUM_VOXEL_TARGET), RoundingMode.UP).doubleValue()); downsampleIndex_ = (int) Math.max(0, Math.round(Math.log(dsFactor) / Math.log(2))); downsampledWidth_ = (int) (tileWidth.multiply(numCols).longValue() / Math.pow(2, downsampleIndex_)); downsampledHeight_ = (int) (tileHeight.multiply(numRows).longValue() / Math.pow(2, downsampleIndex_)); Log.log("Drift compensation DS Index: " + downsampleIndex_, false); Log.log("Drift compensation DS Width: " + downsampledWidth_, false); Log.log("Drift compensation DS Height: " + downsampledHeight_, false); } else { ImageStack lastTPStack = createAFStack(acq_, timeIndex - 1, channelIndex_, downsampledWidth_, downsampledHeight_, downsampleIndex_); ImageStack currentTPStack = createAFStack(acq_, timeIndex, channelIndex_, downsampledWidth_, downsampledHeight_, downsampleIndex_); //run autofocus //image drift is the difference between this TP and the previous one //but does not represent the acutal drift because these 2 TPs will likely have different //positions for the AF compensation Z device //drifteCorrection = move for the AF drive to bring current TP to position of previous TP double driftCorrection = -calcFocusDrift(acq_.getName(), lastTPStack, currentTPStack, acq_.getZStep()); Log.log(acq_.getName() + " Drift compensation: correction = " + driftCorrection, true); //now add in a factor accounting for the previous AF //i.e. how far the reference image is from the desired position driftCorrection += (currentPosition_ - previousPosition_); Log.log(acq_.getName() + " Drift compensation: correction (accounting for previous position) = " + driftCorrection, true); //check if outside max displacement if (Math.abs(currentPosition_ + driftCorrection - initialPosition_) > maxDisplacement_) { Log.log("Calculated focus drift of " + driftCorrection + " um exceeds tolerance. Leaving autofocus offset unchanged", true); return; } Log.log("New position: " + (currentPosition_ + driftCorrection), true); previousPosition_ = currentPosition_; currentPosition_ += driftCorrection; } }
From source file:com.fratello.longevity.smooth.object.SpecialFile.java
private boolean testFilterProperty_Size(SpecialFile other) { String byteType = this.filter.getMetricSize(); BigInteger sourceSize = new BigInteger(String.valueOf(this.SIZE)); BigInteger targetSize = new BigInteger(String.valueOf(other.SIZE)); String num = ""; switch (byteType) { default://w ww.j ava 2 s. c om case "BYTE": num = "1"; break; case "KILOBYTE": num = "1024"; break; case "MEGABYTE": num = "1048576"; break; case "GIGABYTE": num = "1073741824"; break; } sourceSize.multiply(new BigInteger(String.valueOf(num))); targetSize.multiply(new BigInteger(String.valueOf(num))); boolean sourceSizeIsBiggest = sourceSize.compareTo(targetSize) > 0; double requiredPercent = this.filter.getSizePercentMatchDouble(); if (sourceSizeIsBiggest) { double matchPercent = targetSize.divide(sourceSize).doubleValue(); if (!(matchPercent >= requiredPercent)) return false; } else { double matchPercent = sourceSize.divide(targetSize).doubleValue(); if (!(matchPercent >= requiredPercent)) return false; } return true; }
From source file:org.apache.flink.graph.library.clustering.undirected.TriadicCensus.java
@Override public Result getResult() { // vertex metrics BigInteger bigVertexCount = BigInteger.valueOf(vertexMetrics.getResult().getNumberOfVertices()); BigInteger bigEdgeCount = BigInteger.valueOf(vertexMetrics.getResult().getNumberOfEdges()); BigInteger bigTripletCount = BigInteger.valueOf(vertexMetrics.getResult().getNumberOfTriplets()); // triangle count BigInteger bigTriangleCount = BigInteger.valueOf(triangleCount.getResult()); BigInteger one = BigInteger.ONE; BigInteger two = BigInteger.valueOf(2); BigInteger three = BigInteger.valueOf(3); BigInteger six = BigInteger.valueOf(6); // counts as ordered in TriadicCensus.Result BigInteger[] counts = new BigInteger[4]; // triads with three connecting edges = closed triplet = triangle counts[3] = bigTriangleCount;/*from w ww. j a v a 2 s . co m*/ // triads with two connecting edges = open triplet; // deduct each triplet having been counted three times per triangle counts[2] = bigTripletCount.subtract(bigTriangleCount.multiply(three)); // triads with one connecting edge; each edge pairs with `vertex count - 2` vertices // then deduct twice for each open triplet and three times for each triangle counts[1] = bigEdgeCount.multiply(bigVertexCount.subtract(two)).subtract(counts[2].multiply(two)) .subtract(counts[3].multiply(three)); // triads with zero connecting edges; // (vertex count choose 3) minus earlier counts counts[0] = bigVertexCount.multiply(bigVertexCount.subtract(one)).multiply(bigVertexCount.subtract(two)) .divide(six).subtract(counts[1]).subtract(counts[2]).subtract(counts[3]); return new Result(counts); }
From source file:org.apache.accumulo.pig.Bytes.java
/** * Iterate over keys within the passed inclusive range. *///from w w w . j a v a 2 s . c o m public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, final int num) { byte[] aPadded; byte[] bPadded; if (a.length < b.length) { aPadded = padTail(a, b.length - a.length); bPadded = b; } else if (b.length < a.length) { aPadded = a; bPadded = padTail(b, a.length - b.length); } else { aPadded = a; bPadded = b; } if (compareTo(aPadded, bPadded) >= 0) { throw new IllegalArgumentException("b <= a"); } if (num <= 0) { throw new IllegalArgumentException("num cannot be < 0"); } byte[] prependHeader = { 1, 0 }; final BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); final BigInteger diffBI = stopBI.subtract(startBI); final BigInteger splitsBI = BigInteger.valueOf(num + 1); if (diffBI.compareTo(splitsBI) < 0) { return null; } final BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch (Exception e) { LOG.error("Exception caught during division", e); return null; } final Iterator<byte[]> iterator = new Iterator<byte[]>() { private int i = -1; @Override public boolean hasNext() { return i < num + 1; } @Override public byte[] next() { i++; if (i == 0) { return a; } if (i == num + 1) { return b; } BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i))); byte[] padded = curBI.toByteArray(); if (padded[1] == 0) { padded = tail(padded, padded.length - 2); } else { padded = tail(padded, padded.length - 1); } return padded; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return new Iterable<byte[]>() { @Override public Iterator<byte[]> iterator() { return iterator; } }; }
From source file:test.be.fedict.eid.applet.RSATest.java
@Test public void testManualEncryption() throws Exception { while (true) { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); SecureRandom random = new SecureRandom(); int keySize = 128; keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F0), random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey; LOG.debug("private key modulus: " + rsaPrivateKey.getModulus()); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; LOG.debug("public key modulus: " + rsaPublicKey.getModulus()); LOG.debug("public key exponent: " + rsaPublicKey.getPublicExponent()); LOG.debug("modulus size: " + rsaPublicKey.getModulus().toByteArray().length); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); int dataSize = keySize / 8 - 11; byte[] data1 = new byte[dataSize]; for (int i = 0; i < data1.length; i++) { data1[i] = 0x00;/*from w w w . j av a2 s . c o m*/ } byte[] data2 = new byte[dataSize]; for (int i = 0; i < data2.length; i++) { data2[i] = 0x00; } data2[data2.length - 1] = 0x07; byte[] signatureValue1 = cipher.doFinal(data1); LOG.debug("signature size: " + signatureValue1.length); cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] signatureValue2 = cipher.doFinal(data2); BigInteger sigBigInt1 = new BigInteger(signatureValue1); BigInteger sigBigInt2 = new BigInteger(signatureValue2); BigInteger msgBigInt1 = sigBigInt1.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); BigInteger msgBigInt2 = sigBigInt2.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); LOG.debug("msg big int: " + msgBigInt1); byte[] msgBytes1 = msgBigInt1.toByteArray(); LOG.debug("original message size: " + msgBytes1.length); LOG.debug("original message1: " + new String(Hex.encodeHex(msgBytes1))); LOG.debug("original message2: " + new String(Hex.encodeHex(msgBigInt2.toByteArray()))); LOG.debug("msg1 prime: " + msgBigInt1.isProbablePrime(100)); LOG.debug("msg2 prime: " + msgBigInt2.isProbablePrime(100)); // BigInteger.pow offers a very naive implementation LOG.debug("calculating s1^e..."); BigInteger s1_e = sigBigInt1.pow(rsaPublicKey.getPublicExponent().intValue()); LOG.debug("s1^e: " + s1_e); LOG.debug("calculating s2^e..."); BigInteger s2_e = sigBigInt2.pow(rsaPublicKey.getPublicExponent().intValue()); LOG.debug("s2^e: " + s2_e); LOG.debug("calculating GCD..."); LOG.debug("msg1: " + msgBigInt1); LOG.debug("msg2: " + msgBigInt2); BigInteger a = s1_e.subtract(msgBigInt1); BigInteger b = s2_e.subtract(msgBigInt2); LOG.debug("a: " + a); LOG.debug("b: " + b); BigInteger candidateModulus = a.gcd(b); LOG.debug("candidate modulus: " + candidateModulus); LOG.debug("candidate modulus size: " + candidateModulus.toByteArray().length); BigInteger s_e = s1_e.multiply(s2_e); BigInteger m = msgBigInt1.multiply(msgBigInt2); while (false == rsaPublicKey.getModulus().equals(candidateModulus)) { LOG.error("incorrect candidate modulus"); LOG.debug("modulus | candidate modulus: " + candidateModulus.remainder(rsaPublicKey.getModulus()).equals(BigInteger.ZERO)); s_e = s_e.multiply(s1_e); m = m.multiply(msgBigInt1); BigInteger n1 = s_e.subtract(m).gcd(a); BigInteger n2 = s_e.subtract(m).gcd(b); candidateModulus = n1.gcd(n2); // try / 2 LOG.debug("new modulus: " + n1); LOG.debug("new modulus: " + n2); LOG.debug("candidate modulus: " + candidateModulus); LOG.debug("actual mod: " + rsaPublicKey.getModulus()); } } }
From source file:Ternary.java
public Ternary(BigInteger toConvert) { this();/*from w ww . j ava 2 s . c o m*/ int position = 0; BigInteger remaining = toConvert; BigInteger rounded, left; while (!remaining.equals(BigInteger.ZERO)) { rounded = ((new BigDecimal(remaining)).divide(bdThree, 0, BigDecimal.ROUND_HALF_UP)).toBigInteger(); left = remaining.subtract(rounded.multiply(biThree)); if (left.equals(BigInteger.ONE)) setTrit(position++, Trit.POSITIVE); else if (left.equals(BigInteger.ZERO)) setTrit(position++, Trit.NEUTRAL); else setTrit(position++, Trit.NEGATIVE); remaining = rounded; } }
From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java
private void stepThree(final int i) throws Exception { BigInteger n = this.pubKey.getModulus(); BigInteger r; BigInteger upperBound;/*from w w w. j av a 2s .c o m*/ BigInteger lowerBound; BigInteger max; BigInteger min; BigInteger[] tmp; ArrayList<Interval> ms = new ArrayList<>(15); for (Interval interval : this.m) { upperBound = step3ComputeUpperBound(this.si, n, interval.upper); lowerBound = step3ComputeLowerBound(this.si, n, interval.lower); r = lowerBound; // lowerBound <= r <= upperBound while (r.compareTo(upperBound) < 1) { // ceil((2*B+r*n)/si) max = (BigInteger.valueOf(2).multiply(this.bigB)).add(r.multiply(n)); tmp = max.divideAndRemainder(this.si); if (BigInteger.ZERO.compareTo(tmp[1]) != 0) { max = tmp[0].add(BigInteger.ONE); } else { max = tmp[0]; } // floor((3*B-1+r*n)/si min = BigInteger.valueOf(3).multiply(this.bigB); min = min.subtract(BigInteger.ONE); min = min.add(r.multiply(n)); min = min.divide(this.si); // build new interval if (interval.lower.compareTo(max) > 0) { max = interval.lower; } if (interval.upper.compareTo(min) < 0) { min = interval.upper; } if (max.compareTo(min) <= 0) { ms.add(new Interval(max, min)); } // one further.... r = r.add(BigInteger.ONE); } } loggerInstance.log(getClass(), " # of intervals for M" + i + ": " + ms.size(), Logger.LogLevel.INFO); if (ms.size() == 0) { throw new Exception("Zero intervals left, validity oracle seems to be wrong!"); } this.m = ms.toArray(new Interval[ms.size()]); }