Example usage for java.math BigInteger ONE

List of usage examples for java.math BigInteger ONE

Introduction

In this page you can find the example usage for java.math BigInteger ONE.

Prototype

BigInteger ONE

To view the source code for java.math BigInteger ONE.

Click Source Link

Document

The BigInteger constant one.

Usage

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}/*from  ww w . j a  v a  2 s.c  o m*/
 */
@Override
public final int initRsaPrivateKey(final ByteArray primeP, final ByteArray primeQ,
        final ByteArray primeExponentP, final ByteArray primeExponentQ, final ByteArray crtCoefficient)
        throws McbpCryptoException {
    try {
        final BigInteger p = new BigInteger(primeP.toHexString(), 16);
        final BigInteger q = new BigInteger(primeQ.toHexString(), 16);
        final BigInteger dp = new BigInteger(primeExponentP.toHexString(), 16);
        final BigInteger dq = new BigInteger(primeExponentQ.toHexString(), 16);
        final BigInteger a = new BigInteger(crtCoefficient.toHexString(), 16);

        final BigInteger n = p.multiply(q);
        final BigInteger e = dp.modInverse(p.subtract(BigInteger.ONE));

        final BigInteger d = e.modInverse(p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE))
                .divide((p.subtract(BigInteger.ONE)).gcd(q.subtract(BigInteger.ONE))));

        final RSAPrivateKey rsaKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
                .generatePrivate(new RSAPrivateCrtKeySpec(n, e, d, p, q, dp, dq, a));

        initRsaPrivate(rsaKey);

        return n.bitLength() / 8;

    } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new McbpCryptoException(e.toString());
    }
}

From source file:org.candlepin.util.X509CRLStreamWriter.java

protected void writeToEmptyCrl(OutputStream out) throws IOException {
    ASN1InputStream asn1in = null;
    try {/*from   w  w w  . j  a  va 2s . c om*/
        asn1in = new ASN1InputStream(crlIn);
        DERSequence certListSeq = (DERSequence) asn1in.readObject();
        CertificateList certList = new CertificateList(certListSeq);
        X509CRLHolder oldCrl = new X509CRLHolder(certList);

        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(oldCrl.getIssuer(), new Date());
        crlBuilder.addCRL(oldCrl);

        Date now = new Date();
        Date oldNextUpdate = certList.getNextUpdate().getDate();
        Date oldThisUpdate = certList.getThisUpdate().getDate();

        Date nextUpdate = new Date(now.getTime() + (oldNextUpdate.getTime() - oldThisUpdate.getTime()));
        crlBuilder.setNextUpdate(nextUpdate);

        for (Object o : oldCrl.getExtensionOIDs()) {
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) o;
            X509Extension ext = oldCrl.getExtension(oid);

            if (oid.equals(X509Extension.cRLNumber)) {
                DEROctetString octet = (DEROctetString) ext.getValue().getDERObject();
                DERInteger currentNumber = (DERInteger) DERTaggedObject.fromByteArray(octet.getOctets());
                DERInteger nextNumber = new DERInteger(currentNumber.getValue().add(BigInteger.ONE));

                crlBuilder.addExtension(oid, ext.isCritical(), nextNumber);
            } else if (oid.equals(X509Extension.authorityKeyIdentifier)) {
                crlBuilder.addExtension(oid, ext.isCritical(),
                        new AuthorityKeyIdentifierStructure(ext.getValue().getDEREncoded()));
            }
        }

        for (DERSequence entry : newEntries) {
            // XXX: This is all a bit messy considering the user already passed in the serial, date
            // and reason.
            BigInteger serial = ((DERInteger) entry.getObjectAt(0)).getValue();
            Date revokeDate = ((Time) entry.getObjectAt(1)).getDate();
            int reason = CRLReason.unspecified;
            if (entry.size() == 3) {
                X509Extensions extensions = (X509Extensions) entry.getObjectAt(2);
                X509Extension reasonExt = extensions.getExtension(X509Extension.reasonCode);

                if (reasonExt != null) {
                    reason = ((DEREnumerated) reasonExt.getParsedValue()).getValue().intValue();
                }
            }
            crlBuilder.addCRLEntry(serial, revokeDate, reason);
        }

        RSAKeyParameters keyParams = new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent());

        signingAlg = oldCrl.toASN1Structure().getSignatureAlgorithm();
        digestAlg = new DefaultDigestAlgorithmIdentifierFinder().find(signingAlg);

        ContentSigner s;
        try {
            s = new BcRSAContentSignerBuilder(signingAlg, digestAlg).build(keyParams);
            X509CRLHolder newCrl = crlBuilder.build(s);
            out.write(newCrl.getEncoded());
        } catch (OperatorCreationException e) {
            throw new IOException("Could not sign CRL", e);
        }
    } finally {
        IOUtils.closeQuietly(asn1in);
    }
}

From source file:com.amazonaws.services.kinesis.clientlibrary.lib.worker.ShardConsumerTest.java

/**
 * Test method for {@link ShardConsumer#consumeShard()} that starts from initial position of type AT_TIMESTAMP.
 *///from www. j a va2s . c o  m
@Test
public final void testConsumeShardWithInitialPositionAtTimestamp() throws Exception {
    int numRecs = 7;
    BigInteger startSeqNum = BigInteger.ONE;
    Date timestamp = new Date(KinesisLocalFileDataCreator.STARTING_TIMESTAMP + 3);
    InitialPositionInStreamExtended atTimestamp = InitialPositionInStreamExtended
            .newInitialPositionAtTimestamp(timestamp);
    String streamShardId = "kinesis-0-0";
    String testConcurrencyToken = "testToken";
    File file = KinesisLocalFileDataCreator.generateTempDataFile(1, "kinesis-0-", numRecs, startSeqNum,
            "unitTestSCT002");

    IKinesisProxy fileBasedProxy = new KinesisLocalFileProxy(file.getAbsolutePath());

    final int maxRecords = 2;
    final int idleTimeMS = 0; // keep unit tests fast
    ICheckpoint checkpoint = new InMemoryCheckpointImpl(startSeqNum.toString());
    checkpoint.setCheckpoint(streamShardId, ExtendedSequenceNumber.AT_TIMESTAMP, testConcurrencyToken);
    when(leaseManager.getLease(anyString())).thenReturn(null);

    TestStreamlet processor = new TestStreamlet();

    StreamConfig streamConfig = new StreamConfig(fileBasedProxy, maxRecords, idleTimeMS,
            callProcessRecordsForEmptyRecordList, skipCheckpointValidationValue, atTimestamp);

    ShardInfo shardInfo = new ShardInfo(streamShardId, testConcurrencyToken, null,
            ExtendedSequenceNumber.TRIM_HORIZON);
    ShardConsumer consumer = new ShardConsumer(shardInfo, streamConfig, checkpoint, processor, leaseManager,
            parentShardPollIntervalMillis, cleanupLeasesOfCompletedShards, executorService, metricsFactory,
            taskBackoffTimeMillis,
            KinesisClientLibConfiguration.DEFAULT_SKIP_SHARD_SYNC_AT_STARTUP_IF_LEASES_EXIST);

    assertThat(consumer.getCurrentState(),
            is(equalTo(ConsumerStates.ShardConsumerState.WAITING_ON_PARENT_SHARDS)));
    consumer.consumeShard(); // check on parent shards
    Thread.sleep(50L);
    consumer.consumeShard(); // start initialization
    assertThat(consumer.getCurrentState(), is(equalTo(ConsumerStates.ShardConsumerState.INITIALIZING)));
    consumer.consumeShard(); // initialize
    Thread.sleep(50L);

    // We expect to process all records in numRecs calls
    for (int i = 0; i < numRecs;) {
        boolean newTaskSubmitted = consumer.consumeShard();
        if (newTaskSubmitted) {
            LOG.debug("New processing task was submitted, call # " + i);
            assertThat(consumer.getCurrentState(), is(equalTo(ConsumerStates.ShardConsumerState.PROCESSING)));
            // CHECKSTYLE:IGNORE ModifiedControlVariable FOR NEXT 1 LINES
            i += maxRecords;
        }
        Thread.sleep(50L);
    }

    assertThat(processor.getShutdownReason(), nullValue());
    consumer.beginShutdown();
    Thread.sleep(50L);
    assertThat(consumer.getCurrentState(), is(equalTo(ConsumerStates.ShardConsumerState.SHUTTING_DOWN)));
    consumer.beginShutdown();
    assertThat(consumer.getCurrentState(), is(equalTo(ConsumerStates.ShardConsumerState.SHUTDOWN_COMPLETE)));
    assertThat(processor.getShutdownReason(), is(equalTo(ShutdownReason.ZOMBIE)));

    executorService.shutdown();
    executorService.awaitTermination(60, TimeUnit.SECONDS);

    String iterator = fileBasedProxy.getIterator(streamShardId, timestamp);
    List<Record> expectedRecords = toUserRecords(fileBasedProxy.get(iterator, numRecs).getRecords());
    verifyConsumedRecords(expectedRecords, processor.getProcessedRecords());
    assertEquals(4, processor.getProcessedRecords().size());
    file.delete();
}

From source file:com.vvote.verifier.component.votePacking.VotePackingDataStore.java

/**
 * Loads the padding points to be used after vote packing has taken place to
 * ensure all packed votes have the same number of columns
 * //w w  w . j ava 2 s. c  o  m
 * @return true if the padding points are loaded correctly
 * @throws JSONException
 * @throws JSONIOException
 */
private boolean loadPaddingPoints() throws JSONException, JSONIOException {
    String paddingPointFile = IOUtils.findFile(this.getVotePackingConfig().getPaddingFile(),
            this.getBasePath());

    // read padding point for padding the reordered packed plaintext
    // candidate ids
    this.paddingPoint = ECUtils.constructECPointFromJSON(IOUtils.readJSONObjectFromFile(paddingPointFile));

    this.encryptedPaddingPoint = ECUtils.encrypt(this.paddingPoint, this.getPublicKey(), BigInteger.ONE);

    return true;
}

From source file:org.qi4j.runtime.value.CollectionTypeTest.java

private Collection<BigInteger> bigIntegerCollection() {
    Collection<BigInteger> value = new ArrayList<BigInteger>();
    value.add(new BigInteger("-1"));
    value.add(BigInteger.ZERO);/*from   ww  w  . j a v  a 2  s  .co m*/
    value.add(BigInteger.ONE);
    value.add(null);
    value.add(BigInteger.TEN);
    value.add(new BigInteger("-1827368263823729372397239829332"));
    value.add(new BigInteger("2398723982982379827373972398723"));
    return value;
}

From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java

/**
 * Test builder when missing serial number.
 * //w  ww .  java 2s  .  c om
 * @throws Exception
 */
@Test(expectedExceptions = X509CertificateBuilderException.class)
public void testBuilderMissingSerialNumber() throws GeneralSecurityException {
    serial = serial.add(BigInteger.ONE);
    builder.setSubject(SUBJECT_NAME);
    builder.setIssuer(SUBJECT_NAME);
    builder.setNotBefore(notBefore.getTime());
    builder.setNotAfter(notAfter.getTime());
    builder.setPublicKey(keyPair.getPublic());
    builder.build(keyPair.getPrivate());
}

From source file:com.amazonaws.services.kinesis.clientlibrary.proxies.KinesisLocalFileProxy.java

/**
 * {@inheritDoc}/*  w w  w.j  a v  a 2  s.c  o m*/
 */
@Override
public PutRecordResult put(String exclusiveMinimumSequenceNumber, String explicitHashKey, String partitionKey,
        ByteBuffer data) throws ResourceNotFoundException, InvalidArgumentException {
    PutRecordResult output = new PutRecordResult();

    BigInteger startingPosition = BigInteger.ONE;

    if (exclusiveMinimumSequenceNumber != null) {
        startingPosition = new BigInteger(exclusiveMinimumSequenceNumber).add(BigInteger.ONE);
    }

    output.setSequenceNumber(startingPosition.toString());
    return output;
}

From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java

/**
 * Test builder when missing subject./*from w w  w .jav  a2 s.  c o  m*/
 * 
 * @throws Exception
 */
@Test(expectedExceptions = X509CertificateBuilderException.class)
public void testBuilderMissingSubject() throws GeneralSecurityException {
    serial = serial.add(BigInteger.ONE);
    builder.setSerialNumber(serial);
    builder.setIssuer(ISSUER_NAME);
    builder.setNotBefore(notBefore.getTime());
    builder.setNotAfter(notAfter.getTime());
    builder.setPublicKey(keyPair.getPublic());
    builder.build(keyPair.getPrivate());
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

private BigInteger step3ComputeUpperBound(final BigInteger s, final BigInteger modulus,
        final BigInteger upperIntervalBound) {
    BigInteger upperBound = upperIntervalBound.multiply(s);
    upperBound = upperBound.subtract(BigInteger.valueOf(2).multiply(bigB));
    // ceil/*from w w w . ja v  a  2s.c om*/
    BigInteger[] tmp = upperBound.divideAndRemainder(modulus);
    if (BigInteger.ZERO.compareTo(tmp[1]) != 0) {
        upperBound = BigInteger.ONE.add(tmp[0]);
    } else {
        upperBound = tmp[0];
    }

    return upperBound;
}

From source file:org.candlepin.util.X509CRLStreamWriterTest.java

@Test
public void testIncrementsExtensions() throws Exception {
    File crlToChange = writeCRL(createCRL());

    X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange, (RSAPrivateKey) keyPair.getPrivate(),
            (RSAPublicKey) keyPair.getPublic());
    stream.preScan(crlToChange).lock();//from   w  w  w . ja  v  a2  s .  c o  m
    OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile));
    stream.write(o);
    o.close();

    X509CRL changedCrl = readCRL();

    byte[] val = changedCrl.getExtensionValue(X509Extension.cRLNumber.getId());
    DEROctetString s = (DEROctetString) DERTaggedObject.fromByteArray(val);
    DERInteger i = (DERInteger) DERTaggedObject.fromByteArray(s.getOctets());

    assertTrue("CRL Number not incremented", i.getValue().compareTo(BigInteger.ONE) > 0);
}