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:io.getlime.security.powerauth.app.server.service.behavior.SignatureServiceBehavior.java

/**
 * Verify signature for given activation and provided data. Log every validation attempt in the audit log.
 *
 * @param activationId           Activation ID.
 * @param signatureType          Provided signature type.
 * @param signature              Provided signature.
 * @param dataString             String with data used to compute the signature.
 * @param applicationKey         Associated application key.
 * @param keyConversionUtilities Conversion utility class.
 * @return Response with the signature validation result object.
 * @throws UnsupportedEncodingException In case UTF-8 is not supported on the system.
 * @throws InvalidKeySpecException      In case invalid key is provided.
 * @throws InvalidKeyException          In case invalid key is provided.
 *///from  w  ww  .  ja va2s . c  o  m
public VerifySignatureResponse verifySignature(String activationId, String signatureType, String signature,
        String dataString, String applicationKey, CryptoProviderUtil keyConversionUtilities)
        throws UnsupportedEncodingException, InvalidKeySpecException, InvalidKeyException {
    // Prepare current timestamp in advance
    Date currentTimestamp = new Date();

    // Fetch related activation
    ActivationRecordEntity activation = powerAuthRepository.findFirstByActivationId(activationId);

    // Only validate signature for existing ACTIVE activation records
    if (activation != null) {

        // Check the activation - application relationship and version support
        ApplicationVersionEntity applicationVersion = applicationVersionRepository
                .findByApplicationKey(applicationKey);

        if (applicationVersion == null || applicationVersion.getSupported() == false
                || applicationVersion.getApplication().getId() != activation.getApplication().getId()) {

            // Get the data and append application KEY in this case, just for auditing reasons
            byte[] data = (dataString + "&" + applicationKey).getBytes("UTF-8");

            // Increment the counter
            activation.setCounter(activation.getCounter() + 1);

            // Update failed attempts and block the activation, if necessary
            activation.setFailedAttempts(activation.getFailedAttempts() + 1);
            Long remainingAttempts = (activation.getMaxFailedAttempts() - activation.getFailedAttempts());
            if (remainingAttempts <= 0) {
                activation.setActivationStatus(ActivationStatus.BLOCKED);
            }

            // Update the last used date
            activation.setTimestampLastUsed(currentTimestamp);

            // Save the activation
            powerAuthRepository.save(activation);

            auditingServiceBehavior.logSignatureAuditRecord(activation, signatureType, signature, data, false,
                    "activation_invalid_application", currentTimestamp);

            // return the data
            VerifySignatureResponse response = new VerifySignatureResponse();
            response.setActivationId(activationId);
            response.setActivationStatus(ModelUtil.toServiceStatus(ActivationStatus.REMOVED));
            response.setRemainingAttempts(BigInteger.valueOf(0));
            response.setSignatureValid(false);
            response.setUserId("UNKNOWN");

            return response;
        }

        String applicationSecret = applicationVersion.getApplicationSecret();
        byte[] data = (dataString + "&" + applicationSecret).getBytes("UTF-8");

        if (activation.getActivationStatus() == ActivationStatus.ACTIVE) {

            // Get the server private and device public keys
            byte[] serverPrivateKeyBytes = BaseEncoding.base64().decode(activation.getServerPrivateKeyBase64());
            byte[] devicePublicKeyBytes = BaseEncoding.base64().decode(activation.getDevicePublicKeyBase64());
            PrivateKey serverPrivateKey = keyConversionUtilities
                    .convertBytesToPrivateKey(serverPrivateKeyBytes);
            PublicKey devicePublicKey = keyConversionUtilities.convertBytesToPublicKey(devicePublicKeyBytes);

            // Compute the master secret key
            SecretKey masterSecretKey = powerAuthServerKeyFactory
                    .generateServerMasterSecretKey(serverPrivateKey, devicePublicKey);

            // Get the signature keys according to the signature type
            List<SecretKey> signatureKeys = powerAuthServerKeyFactory.keysForSignatureType(signatureType,
                    masterSecretKey);

            // Verify the signature with given lookahead
            boolean signatureValid = false;
            long ctr = activation.getCounter();
            long lowestValidCounter = ctr;
            for (long iterCtr = ctr; iterCtr < ctr
                    + PowerAuthConfiguration.SIGNATURE_VALIDATION_LOOKAHEAD; iterCtr++) {
                signatureValid = powerAuthServerSignature.verifySignatureForData(data, signature, signatureKeys,
                        iterCtr);
                if (signatureValid) {
                    // set the lowest valid counter and break at the lowest
                    // counter where signature validates
                    lowestValidCounter = iterCtr;
                    break;
                }
            }
            if (signatureValid) {

                // Set the activation record counter to the lowest counter
                // (+1, since the client has incremented the counter)
                activation.setCounter(lowestValidCounter + 1);

                // Reset failed attempt count
                activation.setFailedAttempts(0L);

                // Update the last used date
                activation.setTimestampLastUsed(currentTimestamp);

                // Save the activation
                powerAuthRepository.save(activation);

                auditingServiceBehavior.logSignatureAuditRecord(activation, signatureType, signature, data,
                        true, "signature_ok", currentTimestamp);

                // return the data
                VerifySignatureResponse response = new VerifySignatureResponse();
                response.setActivationId(activationId);
                response.setActivationStatus(ModelUtil.toServiceStatus(ActivationStatus.ACTIVE));
                response.setRemainingAttempts(BigInteger.valueOf(activation.getMaxFailedAttempts()));
                response.setSignatureValid(true);
                response.setUserId(activation.getUserId());

                return response;

            } else {

                // Increment the activation record counter
                activation.setCounter(activation.getCounter() + 1);

                // Update failed attempts and block the activation, if
                // necessary
                activation.setFailedAttempts(activation.getFailedAttempts() + 1);
                Long remainingAttempts = (activation.getMaxFailedAttempts() - activation.getFailedAttempts());
                if (remainingAttempts <= 0) {
                    activation.setActivationStatus(ActivationStatus.BLOCKED);
                }

                // Update the last used date
                activation.setTimestampLastUsed(currentTimestamp);

                // Save the activation
                powerAuthRepository.save(activation);

                auditingServiceBehavior.logSignatureAuditRecord(activation, signatureType, signature, data,
                        false, "signature_does_not_match", currentTimestamp);

                // return the data
                VerifySignatureResponse response = new VerifySignatureResponse();
                response.setActivationId(activationId);
                response.setActivationStatus(ModelUtil.toServiceStatus(activation.getActivationStatus()));
                response.setRemainingAttempts(BigInteger.valueOf(remainingAttempts));
                response.setSignatureValid(false);
                response.setUserId(activation.getUserId());

                return response;

            }

        } else {

            // Despite the fact activation is not in active state, increase
            // the counter
            activation.setCounter(activation.getCounter() + 1);

            // Update the last used date
            activation.setTimestampLastUsed(currentTimestamp);

            // Save the activation
            powerAuthRepository.save(activation);

            auditingServiceBehavior.logSignatureAuditRecord(activation, signatureType, signature, data, false,
                    "activation_invalid_state", currentTimestamp);

            // return the data
            VerifySignatureResponse response = new VerifySignatureResponse();
            response.setActivationId(activationId);
            response.setActivationStatus(ModelUtil.toServiceStatus(ActivationStatus.REMOVED));
            response.setRemainingAttempts(BigInteger.valueOf(0));
            response.setSignatureValid(false);
            response.setUserId("UNKNOWN");

            return response;

        }

    } else { // Activation does not exist

        // return the data
        VerifySignatureResponse response = new VerifySignatureResponse();
        response.setActivationId(activationId);
        response.setActivationStatus(ModelUtil.toServiceStatus(ActivationStatus.REMOVED));
        response.setRemainingAttempts(BigInteger.valueOf(0));
        response.setSignatureValid(false);
        response.setUserId("UNKNOWN");

        return response;

    }
}

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

public X509Certificate createClass3EndCert(long sno, X500Name sdn, Map<String, String> exts, PublicKey pubKey,
        KeyPair pKeyPair) throws Exception {
    PublicKey pPubKey = pKeyPair.getPublic();
    PrivateKey pPrivKey = pKeyPair.getPrivate();

    X500Name idn = X500NameUtil.createClass3CaPrincipal();
    BigInteger _sno = BigInteger.valueOf(sno <= 0 ? System.currentTimeMillis() : sno);
    Date nb = new Date(System.currentTimeMillis() - HALF_DAY);
    Date na = new Date(nb.getTime() + FIVE_YEAR);

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(idn, _sno, nb, na, sdn, pubKey);

    addSubjectKID(certBuilder, pubKey);/*from   w  ww .  j  a va  2 s  .  c o m*/
    addAuthorityKID(certBuilder, pPubKey);
    certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(MOST_EKU));
    certBuilder.addExtension(Extension.keyUsage, false, new KeyUsage(END_KEY_USAGE));
    if (exts != null) {
        Set<String> key = exts.keySet();
        for (Iterator<String> it = key.iterator(); it.hasNext();) {
            String oid = it.next();
            String value = exts.get(oid);
            if (!StringUtils.isBlank(value)) {
                certBuilder.addExtension(new ASN1ObjectIdentifier(oid), false,
                        new DEROctetString(value.getBytes()));
            }
        }
    }

    X509Certificate certificate = signCert(certBuilder, pPrivKey);
    certificate.checkValidity(new Date());
    certificate.verify(pPubKey);

    setPKCS9Info(certificate);

    return certificate;
}

From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java

public X509Certificate generateV1Certificate(String subject, char[] ksPass, KeyStore keyStore)
        throws OperatorCreationException, IOException, CertificateException, KeyStoreException,
        NoSuchAlgorithmException {
    KeyPair pair = generateKeyPair();

    BigInteger certSerial = BigInteger.valueOf(System.currentTimeMillis());
    X500Name issuerDN = new X500Name("CN=" + subject);
    X500Name subjectDN = new X500Name("CN=" + subject);
    Date notBefore = new Date(System.currentTimeMillis() - 10000);
    Date notAfter = new Date(System.currentTimeMillis() + 10000);
    PublicKey pubKey = (pair.getPublic());
    X509v1CertificateBuilder certGen = new JcaX509v1CertificateBuilder(issuerDN, certSerial, notBefore,
            notAfter, subjectDN, pubKey);

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").build(pair.getPrivate());
    byte[] encoded = certGen.build(signer).getEncoded();
    CertificateFactory fact = CertificateFactory.getInstance("X.509");
    InputStream is = new ByteArrayInputStream(encoded);
    X509Certificate generateCertificate = (X509Certificate) fact.generateCertificate(is);
    is.close();//from  w ww. j a va 2 s. c  o  m

    // set the CA cert as trusted root
    X509Certificate[] chain = new X509Certificate[] { generateCertificate };
    addToKeyStore(pair, chain, K_NAME, keyStore, ksPass);

    String certStr = generateCertificate.toString();

    return generateCertificate;
}

From source file:gedi.util.math.stat.distributions.OccupancyNumberDistribution.java

private static final BigInteger factorial(int b) {
    if (b == 0)//from w ww .ja v  a 2  s  .  c  o  m
        return BigInteger.ONE;
    BigInteger re = BigInteger.valueOf(b);
    for (int i = b - 1; i > 1; i--)
        re = re.multiply(BigInteger.valueOf(i));
    return re;
}

From source file:com.workday.autoparse.json.demo.InstanceUpdaterTest.java

@Test
public void testBigNumbersFromStrings() {
    TestObject testObject = new TestObject();
    testObject.myBigDecimal = BigDecimal.valueOf(1.1);
    testObject.myBigInteger = BigInteger.valueOf(1);

    Map<String, Object> updates = new HashMap<>();
    updates.put("myBigDecimal", "2.2");
    updates.put("myBigInteger", "2");

    TestObject$$JsonObjectParser.INSTANCE.updateInstanceFromMap(testObject, updates, CONTEXT);

    assertEquals("myBigDecimal", BigDecimal.valueOf(2.2), testObject.myBigDecimal);
    assertEquals("myBigInteger", BigInteger.valueOf(2), testObject.myBigInteger);
}

From source file:com.github.jrrdev.mantisbtsync.core.jobs.issues.IssuesReadersConfiguration.java

/**
 * Return a reader that gets a list of issues ids from a the job parameter mantis.issues_id.
 * The list of issues ids passed in parameter must be separated by a semi-colon.
 *
 * @param authManager/*from  www .  jav  a2  s  .  c  o  m*/
 *          The portal auth manager
 * @param clientStub
 *          Axis client stub
 * @param userName
 *          MantisBT username. If anonymous access is used, should be an empty string.
 * @param password
 *          MantisBT password. If anonymous access is used, should be an empty string.
 * @param issuesIds
 *          Semi-colon separated list of issues ids
 * @return the reader
 */
@Bean
@StepScope
public ListItemReader<BugIdBean> listIssuesReader(final PortalAuthManager authManager,
        final MantisConnectBindingStub clientStub,
        @Value("#{jobParameters['mantis.username']}") final String userName,
        @Value("#{jobParameters['mantis.password']}") final String password,
        @Value("#{jobParameters['mantis.issues_id']}") final String issuesIds) {

    final List<BugIdBean> itemList = new ArrayList<BugIdBean>();
    if (issuesIds != null && !issuesIds.isEmpty()) {
        final String[] strIds = issuesIds.split(";");
        for (final String strId : strIds) {
            final long idValue = Long.valueOf(strId);
            final BugIdBean bean = new BugIdBean();
            bean.setId(BigInteger.valueOf(idValue));
            itemList.add(bean);
        }
    }

    final ListItemReader<BugIdBean> reader = new ListItemReader<BugIdBean>(itemList);
    return reader;
}

From source file:com.bushstar.htmlcoin_android_wallet.ExchangeRatesProvider.java

public static ExchangeRate getExchangeRate(@Nonnull final Cursor cursor) {
    final String currencyCode = cursor
            .getString(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_CURRENCY_CODE));
    final BigInteger rate = BigInteger
            .valueOf(cursor.getLong(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_RATE)));
    final String source = cursor.getString(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_SOURCE));

    return new ExchangeRate(currencyCode, rate, source);
}

From source file:Ternary.java

public BigInteger toBigInteger() {
    BigInteger toRet = BigInteger.ZERO;
    BigInteger curr;/*w w w .  j ava2s.co  m*/
    for (int pos = 0; pos < trits.size(); pos++) {
        curr = (biThree.pow(pos)).multiply(BigInteger.valueOf(getTrit(pos).toInt()));
        toRet = toRet.add(curr);
    }

    return toRet;
}

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

/**
 * @param certificatePublicKey//from w w w.  ja  v a 2  s  .com
 * @param caPrivateKey
 * @param issuer
 * @param subject
 *
 * @return
 */
public static X509Certificate generateServerCertificate(PublicKey certificatePublicKey, PrivateKey caPrivateKey,
        X509Name issuer, X509Name subject) throws Exception {
    X509Certificate cert = null;

    X509V3CertificateGenerator gen = new X509V3CertificateGenerator();
    gen.setIssuerDN(issuer);
    gen.setSubjectDN(subject);
    setNotBeforeNotAfter(gen, 10); // validity from 48 hours in the past until 10 years in the future
    gen.setPublicKey(certificatePublicKey);
    gen.setSignatureAlgorithm(getSignatureAlgorithm());
    gen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    gen = addSSLServerExtensions(gen);

    cert = gen.generate(caPrivateKey, "BC");
    return cert;
}

From source file:burstcoin.jminer.core.round.Round.java

/**
 * Handle message.//from   ww  w  .  j  a v a  2 s.c  om
 *
 * @param event the event
 */
@EventListener
public void handleMessage(CheckerResultEvent event) {
    if (blockNumber == event.getBlockNumber()) {
        // check new lowest result
        if (event.getResult() != null) {
            long nonce = event.getNonce();
            BigInteger deadline = event.getResult().divide(BigInteger.valueOf(baseTarget));
            long calculatedDeadline = deadline.longValue();

            if (devPool) {
                if (calculatedDeadline < targetDeadline) {
                    // remember for next triggered commit
                    devPoolResults.add(new DevPoolResult(event.getBlockNumber(), calculatedDeadline,
                            event.getNonce(), event.getChunkPartStartNonce()));
                } else {
                    // todo there will be a lot of skipped, makes no sense, cause lowest not used here, remove or make adjustable by setting.
                    //            publisher.publishEvent(new RoundSingleResultSkippedEvent(this, event.getBlockNumber(), nonce, event.getChunkPartStartNonce(), calculatedDeadline,
                    //                                                                     targetDeadline, poolMining));
                    runningChunkPartStartNonces.remove(event.getChunkPartStartNonce());
                    triggerFinishRoundEvent(event.getBlockNumber());
                }
            } else {
                if (event.getResult().compareTo(lowest) < 0) {
                    lowest = event.getResult();
                    if (calculatedDeadline < targetDeadline) {
                        network.commitResult(blockNumber, calculatedDeadline, nonce,
                                event.getChunkPartStartNonce(), plots.getSize());

                        // ui event
                        fireEvent(new RoundSingleResultEvent(this, event.getBlockNumber(), nonce,
                                event.getChunkPartStartNonce(), calculatedDeadline, poolMining));
                    } else {
                        // ui event
                        fireEvent(new RoundSingleResultSkippedEvent(this, event.getBlockNumber(), nonce,
                                event.getChunkPartStartNonce(), calculatedDeadline, targetDeadline,
                                poolMining));
                        // chunkPartStartNonce finished
                        runningChunkPartStartNonces.remove(event.getChunkPartStartNonce());
                        triggerFinishRoundEvent(event.getBlockNumber());
                    }
                } else {
                    // chunkPartStartNonce finished
                    runningChunkPartStartNonces.remove(event.getChunkPartStartNonce());
                    triggerFinishRoundEvent(event.getBlockNumber());
                }
            }
        } else {
            LOG.error("CheckerResultEvent result == null");
        }
    } else {
        LOG.trace("event for previous block ...");
    }
}