Example usage for java.math BigInteger valueOf

List of usage examples for java.math BigInteger valueOf

Introduction

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

Prototype

private static BigInteger valueOf(int val[]) 

Source Link

Document

Returns a BigInteger with the given two's complement representation.

Usage

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

private void stepTwoA() throws Exception {
    byte[] send;//from   w w  w  .  j  av a 2s  .  com
    BigInteger n = this.pubKey.getModulus();

    loggerInstance.log(getClass(), "Step 2a: Starting the search", Logger.LogLevel.INFO);

    // si = ceil(n/(3B))
    BigInteger tmp[] = n.divideAndRemainder(BigInteger.valueOf(3).multiply(bigB));
    if (BigInteger.ZERO.compareTo(tmp[1]) != 0) {
        this.si = tmp[0].add(BigInteger.ONE);
    } else {
        this.si = tmp[0];
    }

    // correction will be done in do while
    this.si = this.si.subtract(BigInteger.ONE);

    IHttpRequestResponse response;
    byte[] request;

    do {
        // Check if user has cancelled the worker
        if (isCancelled()) {
            loggerInstance.log(getClass(), "Decryption Attack Executor Worker cancelled by user",
                    Logger.LogLevel.INFO);
            return;
        }

        this.si = this.si.add(BigInteger.ONE);
        send = prepareMsg(this.c0, this.si);

        request = this.requestResponse.getRequest();
        String[] components = Decoder.getComponents(this.parameter.getJoseValue());
        components[1] = Decoder.base64UrlEncode(send);

        String newComponentsConcatenated = Decoder.concatComponents(components);

        request = JoseParameter.updateRequest(request, this.parameter, helpers, newComponentsConcatenated);

        response = callbacks.makeHttpRequest(this.httpService, request);
        updateAmountRequest();

    } while (oracle.getResult(response.getResponse()) != BleichenbacherPkcs1Oracle.Result.VALID);
    loggerInstance.log(getClass(), "Matching response: " + helpers.bytesToString(response.getResponse()),
            Logger.LogLevel.DEBUG);
}

From source file:com.vmware.demo.SamlUtils.java

/**
 * Generate a public x509 cert, based on a key.
 *
 * @param key KeyPair used to generate public Cert, private key in KeyPair not exposed.
 * @param issuer If generating an SSL Cert, issuer needs to match hostname
 * @return/*w ww  . j  ava 2 s.  c o m*/
 * @throws SamlException
 */
public static X509Certificate generateCert(KeyPair key, String issuer) throws SamlException {
    X509Certificate binCert;
    try {
        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        // create the certificate - version 3
        v3CertGen.reset();
        v3CertGen.setSerialNumber(BigInteger.valueOf(1));
        v3CertGen.setIssuerDN(new X509Principal(issuer));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis()));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); //10 years
        v3CertGen.setSubjectDN(new X509Principal(issuer));
        v3CertGen.setPublicKey(key.getPublic());
        v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

        // add the extensions
        v3CertGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.BasicConstraints, false,
                new BasicConstraints(true));

        // generate the actual cert
        binCert = v3CertGen.generate(key.getPrivate());

        // check the cert
        binCert.checkValidity(new Date());
        binCert.verify(key.getPublic());
    } catch (Exception e) {
        throw new SamlException("Failed to generate certificate.", e);
    }

    return binCert;
}

From source file:co.rsk.remasc.Remasc.java

private void payIncludedSiblings(List<Sibling> siblings, BigInteger topReward) {
    long perLateBlockPunishmentDivisor = remascConstants.getLateUncleInclusionPunishmentDivisor();
    for (Sibling sibling : siblings) {
        long processingBlockNumber = executionBlock.getNumber() - remascConstants.getMaturity();
        long numberOfBlocksLate = sibling.getIncludedHeight() - processingBlockNumber - 1L;
        BigInteger lateInclusionPunishment = topReward.multiply(BigInteger.valueOf(numberOfBlocksLate))
                .divide(BigInteger.valueOf(perLateBlockPunishmentDivisor));
        transfer(sibling.getCoinbase(), topReward.subtract(lateInclusionPunishment));
        provider.addToBurnBalance(lateInclusionPunishment);
    }/*  w ww.  j a v a  2s.  c  om*/
}

From source file:de.jfachwert.post.Postfach.java

/**
 * Liefert die Postfach-Nummer als formattierte Zahl. Dies macht natuerlich
 * nur Sinn, wenn diese Nummer gesetzt ist. Daher wird eine
 * {@link IllegalStateException} geworfen, wenn dies nicht der Fall ist.
 *
 * @return z.B. "8 15"//from w  ww.  j a  v a 2  s.  co  m
 */
@SuppressWarnings("squid:S3655")
public String getNummerFormatted() {
    if (!this.getNummer().isPresent()) {
        throw new IllegalStateException("no number present");
    }
    BigInteger hundert = BigInteger.valueOf(100);
    StringBuilder formatted = new StringBuilder();
    for (BigInteger i = this.getNummer().get(); i.compareTo(BigInteger.ONE) > 0; i = i.divide(hundert)) {
        formatted.insert(0, " " + i.remainder(hundert));
    }
    return formatted.toString().trim();
}

From source file:Peer.java

@Override
public boolean insert(String word, String def, Level logLevel) throws Exception {
    lg.log(Level.FINEST, "insert Entry");

    // Max key value
    Key max = new Key(BigInteger.valueOf((int) Math.pow(2, hasher.getBitSize()))).pred();

    // Get key hash 
    Key key = hasher.getHash(word);

    lg.log(Level.FINER, " Hashed word " + word + " with definition " + def + " has key " + key);

    // If this peer knows the which peer that key belongs to ...
    if (//from  w w  w  .  jav  a 2 s  .c o  m
    // Normal ascending rande
    pred == null || (key.compare(pred) > 0 && key.compare(nodeid) <= 0)
    // Modulo range 
            || (pred.compare(nodeid) > 0 && (key.compare(pred) > 0 && key.compare(max) <= 0)
                    || (key.compare(nodeid) <= 0))) {
        lg.log(logLevel,
                "(insert)Peer " + nodeid + " should have word " + word + "(" + def + ") with key " + key);
        dict.put(word, def);
        lg.log(Level.FINEST, "insert Exit");
        return true;
    }

    // ... else find the successor through the finer table
    Key closestNode = ft.getClosestSuccessor(key);

    lg.log(logLevel, "(insert)Peer " + nodeid + " should NOT have word " + word + "(" + def + ") with key "
            + key + " ... calling insert on the best finger table match " + closestNode);

    PeerInterface peer = getPeer(closestNode);
    lg.log(Level.FINEST, "insert Exit");
    return peer.insert(word, def, logLevel);
}

From source file:com.cognitect.transit.TransitTest.java

public void testReadRatio() throws IOException {

    Ratio r = (Ratio) reader("{\"~#ratio\": [\"~n1\",\"~n2\"]}").read();

    assertEquals(BigInteger.valueOf(1), r.getNumerator());
    assertEquals(BigInteger.valueOf(2), r.getDenominator());
    assertEquals(0.5d, r.getValue().doubleValue(), 0.01d);
}

From source file:com.peterphi.std.crypto.keygen.CaHelper.java

/**
 * @param kp//  w w w.  j  a  va 2 s  .  com
 * @param issuer
 * @param subject
 *
 * @return
 */
public static X509Certificate generateCaCertificate(final String friendlyName, final KeyPair kp,
        final BigInteger serial, final X509Name issuer, final X509Name subject) throws Exception {

    X509Certificate cert = null;

    X509V3CertificateGenerator gen = new X509V3CertificateGenerator();
    gen.setIssuerDN(issuer);
    setNotBeforeNotAfter(gen, 20); // The CA certificate is valid for 20 years
    gen.setSubjectDN(subject);
    gen.setPublicKey(kp.getPublic());
    gen.setSignatureAlgorithm(getSignatureAlgorithm());

    if (serial != null)
        gen.setSerialNumber(serial);
    else
        gen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));

    gen = addCaExtensions(gen, kp.getPublic());
    // gen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
    // new SubjectKeyIdentifierStructure(kp.getPublic()));
    cert = gen.generate(kp.getPrivate(), "BC");

    cert.checkValidity();
    cert.verify(kp.getPublic(), "BC");

    if (friendlyName != null) {
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName));
    }

    return cert;
}

From source file:org.archive.bdb.BdbModule.java

protected void setup(File f, boolean create) throws DatabaseException, IOException {
    EnvironmentConfig config = new EnvironmentConfig();
    config.setAllowCreate(create);//from  w  w  w.  j a  va 2  s.  c o  m
    config.setLockTimeout(75, TimeUnit.MINUTES); // set to max

    if (getCacheSize() > 0) {
        config.setCacheSize(getCacheSize());
        if (getCachePercent() > 0) {
            LOGGER.warning("cachePercent and cacheSize are both set. Only cacheSize will be used.");
        }
    } else if (getCachePercent() > 0) {
        config.setCachePercent(getCachePercent());
    }

    config.setSharedCache(getUseSharedCache());

    // we take the advice literally from...
    // http://www.oracle.com/technology/products/berkeley-db/faq/je_faq.html#33
    long nLockTables = getExpectedConcurrency() - 1;
    while (!BigInteger.valueOf(nLockTables).isProbablePrime(Integer.MAX_VALUE)) {
        nLockTables--;
    }
    config.setConfigParam("je.lock.nLockTables", Long.toString(nLockTables));

    // triple this value to 6K because stats show many faults
    config.setConfigParam("je.log.faultReadSize", "6144");

    if (!getUseHardLinkCheckpoints()) {
        // to support checkpoints by textual manifest only, 
        // prevent BDB's cleaner from deleting log files
        config.setConfigParam("je.cleaner.expunge", "false");
    } // else leave whatever other setting was already in place

    org.archive.util.FileUtils.ensureWriteableDirectory(f);
    this.bdbEnvironment = new EnhancedEnvironment(f, config);
    this.classCatalog = this.bdbEnvironment.getClassCatalog();
    if (!create) {
        // freeze last log file -- so that originating checkpoint isn't fouled
        DbBackup dbBackup = new DbBackup(bdbEnvironment);
        dbBackup.startBackup();
        dbBackup.endBackup();
    }
}

From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java

public X509Certificate signCert(PKCS10CertificationRequest pkcs10CSR, X500Name issuer, KeyPair pKeyPair)
        throws Exception {
    SubjectPublicKeyInfo pkInfo = pkcs10CSR.getSubjectPublicKeyInfo();
    RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo);
    RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
    KeyFactory kf = KeyFactory.getInstance(ALG_RSA);
    PublicKey publicKey = kf.generatePublic(rsaSpec);

    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publicKey.getEncoded()));
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer,
            BigInteger.valueOf(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() - DateConstant.ONE_DAY),
            new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR), pkcs10CSR.getSubject(), keyInfo);

    ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER)
            .build(pKeyPair.getPrivate());
    X509Certificate signedCert = new JcaX509CertificateConverter().setProvider(JCE_PROVIDER)
            .getCertificate(certBuilder.build(signer));
    signedCert.verify(pKeyPair.getPublic());

    return signedCert;
}