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:main.java.utils.Utility.java

public static String asUnsignedDecimalString(long l) {
    /** the constant 2^64 */
    BigInteger TWO_64 = BigInteger.ONE.shiftLeft(64);
    BigInteger b = BigInteger.valueOf(l);

    if (b.signum() < 0) {
        b = b.add(TWO_64);//from w w w.ja v  a 2 s  .c  o  m
    }

    return b.toString();
}

From source file:org.cryptomath.CryptoMath.java

public static String subtract(final String a, final String b, final String alias) throws CryptoMathException {
    try {/*from  w  ww .  j  av  a 2 s  . c  om*/
        logger.info(MessageFormat.format("Retrieving key pair for {0}", alias));
        PaillierFunctionUtil util = new PaillierFunctionUtil();
        CustomKeyPair kp = (CustomKeyPair) util.getKeyPair(alias);

        EncryptedInteger ea = new EncryptedInteger(kp.getPublicKey());
        ea.setCipherVal(new BigInteger(a));

        EncryptedInteger eb = new EncryptedInteger(kp.getPublicKey());
        eb.setCipherVal(new BigInteger(b));

        eb = eb.multiply(BigInteger.ONE.negate());

        logger.info("Adding encrypted values");
        EncryptedInteger value = ea.add(eb);

        return value.getCipherVal().toString();
    } catch (KeyGenerationException | BigIntegerClassNotValid | PublicKeysNotEqualException ex) {
        logger.error("Adding given values failed", ex);
        throw new CryptoMathException("Adding given values failed", ex);
    }
}

From source file:org.openestate.io.trovit.TrovitUtils.java

public static IntBool parseIntBool(String value) {
    value = StringUtils.trimToNull(value);

    if (value == null)
        return null;
    else if ("0".equalsIgnoreCase(value))
        return new IntBool(BigInteger.ZERO);
    else if ("1".equalsIgnoreCase(value))
        return new IntBool(BigInteger.ONE);

    try {/*from   w w w.  j a v a  2 s.  c o  m*/
        Boolean boolValue = parseBool(value);
        if (boolValue != null)
            return new IntBool(boolValue);
    } catch (Exception ex) {
    }

    try {
        BigInteger intValue = DatatypeConverter.parseInteger(value);
        if (intValue != null)
            return new IntBool(intValue);
    } catch (Exception ex) {
    }

    throw new IllegalArgumentException("Can't parse int-bool value '" + value + "'!");
}

From source file:com.github.jrrdev.mantisbtsync.core.services.JdbcIssuesServiceTest.java

/**
 * Test method for {@link com.github.jrrdev.mantisbtsync.core.services.JdbcIssuesService#insertStatusIfNotExists(biz.futureware.mantis.rpc.soap.client.ObjectRef)}.
 *///from www  .j a v  a 2s  . com
@Test
public void testInsertStatusIfNotExists() {
    final ObjectRef item = new ObjectRef(BigInteger.ONE, "item");
    final boolean result = dao.insertStatusIfNotExists(item);
    assertTrue(result);

    final List<ObjectRef> list = getJdbcTemplate().query("SELECT id, name FROM mantis_enum_status",
            new BeanPropertyRowMapper<ObjectRef>(ObjectRef.class));

    assertEquals(1, list.size());
    assertEquals(item, list.get(0));

    final boolean result2 = dao.insertStatusIfNotExists(item);
    assertTrue(result2);
}

From source file:org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.POCast.java

@Override
public Result getNextBigInteger() throws ExecException {
    PhysicalOperator in = inputs.get(0);
    Byte resultType = in.getResultType();
    switch (resultType) {
    case DataType.BAG:
    case DataType.TUPLE:
    case DataType.MAP:
    case DataType.DATETIME:
        return error();

    case DataType.BYTEARRAY: {
        DataByteArray dba;//from  ww  w  .ja  va  2  s.  c om
        Result res = in.getNextDataByteArray();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            try {
                dba = (DataByteArray) res.result;
            } catch (ClassCastException e) {
                // res.result is not of type ByteArray. But it can be one of the types from which cast is still possible.
                if (realType == null) {
                    // Find the type and cache it.
                    realType = DataType.findType(res.result);
                }
                try {
                    res.result = DataType.toBigInteger(res.result, realType);
                } catch (ClassCastException cce) {
                    // Type has changed. Need to find type again and try casting it again.
                    realType = DataType.findType(res.result);
                    res.result = DataType.toBigInteger(res.result, realType);
                }
                return res;
            }
            try {
                if (null != caster) {
                    res.result = caster.bytesToBigInteger(dba.get());
                } else {
                    int errCode = 1075;
                    String msg = unknownByteArrayErrorMessage + "BigInteger.";
                    throw new ExecException(msg, errCode, PigException.INPUT);
                }
            } catch (ExecException ee) {
                throw ee;
            } catch (IOException e) {
                log.error("Error while casting from ByteArray to BigInteger");
            }
        }
        return res;
    }

    case DataType.BOOLEAN: {
        Result res = in.getNextBoolean();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            if ((Boolean) res.result) {
                res.result = BigInteger.ONE;
            } else {
                res.result = BigInteger.ZERO;
            }
        }
        return res;
    }
    case DataType.INTEGER: {
        Result res = in.getNextInteger();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            res.result = BigInteger.valueOf(((Integer) res.result).longValue());
        }
        return res;
    }

    case DataType.DOUBLE: {
        Result res = in.getNextDouble();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            res.result = BigInteger.valueOf(((Double) res.result).longValue());
        }
        return res;
    }

    case DataType.LONG: {
        Result res = in.getNextLong();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            res.result = BigInteger.valueOf(((Long) res.result).longValue());
        }
        return res;
    }

    case DataType.FLOAT: {
        Result res = in.getNextFloat();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            res.result = BigInteger.valueOf(((Float) res.result).longValue());
        }
        return res;
    }

    case DataType.CHARARRAY: {
        Result res = in.getNextString();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            res.result = new BigInteger((String) res.result);
        }
        return res;
    }

    case DataType.BIGINTEGER: {
        return in.getNextBigInteger();
    }

    case DataType.BIGDECIMAL: {
        Result res = in.getNextBigDecimal();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            res.result = ((BigDecimal) res.result).toBigInteger();
        }
        return res;
    }

    }

    return error();
}

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

private void stepTwoA() throws Exception {
    byte[] send;/*  w  w w. j  av a  2 s  . co m*/
    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:org.apache.xml.security.stax.ext.XMLSecurityUtils.java

public static void createKeyValueTokenStructure(AbstractOutputProcessor abstractOutputProcessor,
        OutputProcessorChain outputProcessorChain, PublicKey publicKey)
        throws XMLStreamException, XMLSecurityException {

    if (publicKey == null) {
        throw new XMLSecurityException("stax.signature.publicKeyOrCertificateMissing");
    }//from w  w  w . j  a  va 2  s  .c o m

    String algorithm = publicKey.getAlgorithm();

    abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
            XMLSecurityConstants.TAG_dsig_KeyValue, true, null);

    if ("RSA".equals(algorithm)) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_RSAKeyValue, false, null);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Modulus, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(rsaPublicKey.getModulus().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Modulus);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Exponent, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(rsaPublicKey.getPublicExponent().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Exponent);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_RSAKeyValue);
    } else if ("DSA".equals(algorithm)) {
        DSAPublicKey dsaPublicKey = (DSAPublicKey) publicKey;
        BigInteger j = dsaPublicKey.getParams().getP().subtract(BigInteger.ONE)
                .divide(dsaPublicKey.getParams().getQ());
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_DSAKeyValue, false, null);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_P, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(dsaPublicKey.getParams().getP().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_P);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Q, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(dsaPublicKey.getParams().getQ().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Q);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_G, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(dsaPublicKey.getParams().getG().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_G);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Y, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(dsaPublicKey.getY().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Y);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_J, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(j.toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_J);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_DSAKeyValue);
    } else if ("EC".equals(algorithm)) {
        ECPublicKey ecPublicKey = (ECPublicKey) publicKey;

        List<XMLSecAttribute> attributes = new ArrayList<XMLSecAttribute>(1);
        attributes.add(abstractOutputProcessor.createAttribute(XMLSecurityConstants.ATT_NULL_URI,
                "urn:oid:" + ECDSAUtils.getOIDFromPublicKey(ecPublicKey)));
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_ECKeyValue, true, null);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_NamedCurve, false, attributes);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_NamedCurve);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_PublicKey, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(
                        ECDSAUtils.encodePoint(ecPublicKey.getW(), ecPublicKey.getParams().getCurve())));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_PublicKey);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_ECKeyValue);
    }

    abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
            XMLSecurityConstants.TAG_dsig_KeyValue);
}

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 ww w.j ava 2 s. c o 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:org.apache.cassandra.cql.jdbc.HandleObjects.java

private static final BigInteger objectToBITorTINYINTorSMALLINTorNUMERIC(Class<? extends Object> objectClass,
        Object object) {//w  w w  .  j av  a2  s.  c  o  m
    // Strings should always work
    if (objectClass == String.class)
        return new BigInteger((String) object);

    // Booleans are either false=0 or true=1
    if (objectClass == Boolean.class)
        return ((Boolean) object) == false ? BigInteger.ZERO : BigInteger.ONE;

    // All the integer (non floating-point) are simple
    if (objectClass == Integer.class)
        return BigInteger.valueOf((Integer) object);
    else if (objectClass == BigInteger.class)
        return ((BigInteger) object);
    else if (objectClass == Long.class)
        return BigInteger.valueOf(((Long) object));
    else if (objectClass == Short.class)
        return BigInteger.valueOf(((Short) object).longValue());
    else if (objectClass == Byte.class)
        return BigInteger.valueOf(((Byte) object).longValue());

    // Floating ones need to just pass the integer part
    else if (objectClass == Double.class)
        return BigInteger.valueOf(((Double) object).longValue());
    else if (objectClass == Float.class)
        return BigInteger.valueOf(((Float) object).longValue());
    else if (objectClass == BigDecimal.class)
        return BigInteger.valueOf(((BigDecimal) object).intValue());
    else
        return null; // this should not happen
}

From source file:org.jembi.rhea.transformers.XDSRegistryStoredQueryResponse.java

protected String generateATNAMessage(String request, String patientId, String uniqueId, boolean outcome)
        throws JAXBException {
    AuditMessage res = new AuditMessage();

    EventIdentificationType eid = new EventIdentificationType();
    eid.setEventID(ATNAUtil.buildCodedValueType("DCM", "110112", "Query"));
    eid.setEventActionCode("E");
    eid.setEventDateTime(ATNAUtil.newXMLGregorianCalendar());
    eid.getEventTypeCode()//  w w  w  .j  a  va  2 s. co  m
            .add(ATNAUtil.buildCodedValueType("IHE Transactions", "ITI-18", "Registry Stored Query"));
    eid.setEventOutcomeIndicator(outcome ? BigInteger.ONE : BigInteger.ZERO);
    res.setEventIdentification(eid);

    res.getActiveParticipant().add(ATNAUtil.buildActiveParticipant(ATNAUtil.WSA_REPLYTO_ANON,
            ATNAUtil.getProcessID(), true, ATNAUtil.getHostIP(), (short) 2, "DCM", "110153", "Source"));
    res.getActiveParticipant().add(ATNAUtil.buildActiveParticipant(buildRegistryPath(), xdsRegistryHost, false,
            xdsRegistryHost, (short) 1, "DCM", "110152", "Destination"));

    res.getAuditSourceIdentification().add(ATNAUtil.buildAuditSource("openhie-registry"));

    res.getParticipantObjectIdentification()
            .add(ATNAUtil.buildParticipantObjectIdentificationType(
                    String.format("%s^^^&%s&ISO", patientId, requestedAssigningAuthority), (short) 1, (short) 1,
                    "RFC-3881", "2", "PatientNumber", null));

    List<ParticipantObjectDetail> pod = new ArrayList<ParticipantObjectDetail>();
    pod.add(new ParticipantObjectDetail("QueryEncoding", "UTF-8".getBytes()));
    if (homeCommunityId != null)
        pod.add(new ParticipantObjectDetail("urn:ihe:iti:xca:2010:homeCommunityId",
                homeCommunityId.getBytes()));

    res.getParticipantObjectIdentification().add(ATNAUtil.buildParticipantObjectIdentificationType(uniqueId,
            (short) 2, (short) 24, "IHE Transactions", "ITI-18", "Registry Stored Query", request, pod));

    return ATNAUtil.marshallATNAObject(res);
}