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:im.whistle.crypt.Crypt.java

/**
 * Generates a private/public key pair./*  ww w  . ja v a 2  s  . co  m*/
 * @param args Arguments, element at 0 is the key size
 * @param callback Callback
 */
public static void genkeys(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        Log.i("whistle", "Generating key pair ...");
        PRNGProvider.init(); // Ensure OpenSSL fix
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        int bits = args.getInt(0);
        int exp = args.getInt(1);
        keyPairGenerator.initialize(new RSAKeyGenParameterSpec(bits, BigInteger.valueOf(exp)));
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        String priv = "-----BEGIN RSA PRIVATE KEY-----\n"
                + Base64.encodeToString(keyPair.getPrivate().getEncoded(), Base64.DEFAULT).trim()
                + "\n-----END RSA PRIVATE KEY-----";
        String pub = "-----BEGIN PUBLIC KEY-----\n"
                + Base64.encodeToString(keyPair.getPublic().getEncoded(), Base64.DEFAULT).trim()
                + "\n-----END PUBLIC KEY-----";
        JSONArray res = new JSONArray();
        res.put(priv);
        res.put(pub);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Key pair generation failed: " + ex.getMessage());
        callback.error(ex);
    }
}

From source file:NumberInRange.java

public static boolean isInRange(Number number, BigInteger min, BigInteger max) {
    try {//from   w  ww.  j  a  va2  s  . c om
        BigInteger bigInteger = null;
        if (number instanceof Byte || number instanceof Short || number instanceof Integer
                || number instanceof Long) {
            bigInteger = BigInteger.valueOf(number.longValue());
        } else if (number instanceof Float || number instanceof Double) {
            bigInteger = new BigDecimal(number.doubleValue()).toBigInteger();
        } else if (number instanceof BigInteger) {
            bigInteger = (BigInteger) number;
        } else if (number instanceof BigDecimal) {
            bigInteger = ((BigDecimal) number).toBigInteger();
        } else {
            // not a standard number
            bigInteger = new BigDecimal(number.doubleValue()).toBigInteger();
        }
        return max.compareTo(bigInteger) >= 0 && min.compareTo(bigInteger) <= 0;
    } catch (NumberFormatException e) {
        return false;
    }
}

From source file:org.springframework.cloud.consul.bus.EventService.java

private void setLastIndex(Response<?> response) {
    Long consulIndex = response.getConsulIndex();
    if (consulIndex != null) {
        lastIndex.set(BigInteger.valueOf(consulIndex));
    }/*from w w w .  jav a2  s.  c o  m*/
}

From source file:cherry.foundation.crypto.SecureBigIntegerEncoderTest.java

@Test
public void testSecureBigInteger() throws Exception {
    SecureBigInteger.setEncoder(createSecureBigIntegerEncoder());
    for (int i = 0; i < 100; i++) {

        BigInteger plain = BigInteger.valueOf(random.nextInt());
        SecureBigInteger ss0 = SecureBigInteger.plainValueOf(plain);
        assertThat(ss0.plain(), is(plain));
        assertThat(ss0.crypto(), is(not(plain.toString())));

        SecureBigInteger ss1 = SecureBigInteger.cryptoValueOf(ss0.crypto());
        assertThat(ss1.plain(), is(plain));
        assertThat(ss1.crypto(), is(ss0.crypto()));

        SecureBigInteger ss2 = SecureBigInteger.plainValueOf(ss1.plain());
        assertThat(ss2.plain(), is(plain));
        assertThat(ss2.crypto(), is(ss0.crypto()));

        SecureBigInteger ss3 = SecureBigInteger.cryptoValueOf(ss2.crypto());
        assertThat(ss3.plain(), is(plain));
        assertThat(ss3.crypto(), is(ss0.crypto()));
    }//from  w w  w  . j av a2  s.co m
}

From source file:com.github.tell.arithmetic.integer.gmp.MPZBenchmarking.java

@SuppressWarnings("UnusedAssignment")
private static StopWatch mulWithBigInteger(final int length) {
    final BigInteger x1 = new BigInteger(length, secureRandom);
    final BigInteger x2 = new BigInteger(length, secureRandom);

    @SuppressWarnings("unused")
    BigInteger x3 = BigInteger.valueOf(0);
    final StopWatch timer = new StopWatch();
    timer.start();//from  w w  w.ja  v a  2 s . com
    for (int j = 0; j < numOfLoop; j++) {
        x3 = x1.multiply(x2);
    }
    timer.stop();

    printout(timer, length, "BigInteger");

    return timer;
}

From source file:DiffieHellman.java

/**
 * Generates a random private Key (element 0) and a random public key (element 1) 
 * from the given {@code modulus}./*from  w w  w.  j av  a 2s .co  m*/
 * 
 * @param modulus
 * @return BigInteger array.  Element 0 is privateKey.  Element 1 is publicKey.
 */
public BigInteger[] generateRandomKeys(BigInteger modulus) {
    BigInteger privateKey = BigInteger.valueOf(System.currentTimeMillis() + __loadTime);
    return new BigInteger[] { privateKey, generatePublicKey(privateKey, modulus) };
}

From source file:Bytes.java

public static String friendly(long bytes) {
    return friendly(Bytes.B, BigInteger.valueOf(bytes));
}

From source file:fr.xebia.demo.objectgrid.ticketing.Seat.java

public Seat(int id, int number, boolean booked, int price) {
    super();/*  w w  w.j a va2  s . c o  m*/
    this.id = id;
    this.number = number;
    this.booked = booked;
    this.price = BigInteger.valueOf(price);
}

From source file:be.fedict.trust.service.util.ClockDriftUtil.java

public static Date executeTSP(ClockDriftConfigEntity clockDriftConfig, NetworkConfig networkConfig)
        throws IOException, TSPException {

    LOG.debug("clock drift detection: " + clockDriftConfig.toString());

    TimeStampRequestGenerator requestGen = new TimeStampRequestGenerator();

    TimeStampRequest request = requestGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100));
    byte[] requestData = request.getEncoded();

    HttpClient httpClient = new HttpClient();

    if (null != networkConfig) {
        httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort());
    }/*w  ww.  j a v a 2  s  .  c o m*/

    PostMethod postMethod = new PostMethod(clockDriftConfig.getServer());
    postMethod.setRequestEntity(new ByteArrayRequestEntity(requestData, "application/timestamp-query"));

    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode != HttpStatus.SC_OK) {
        throw new TSPException("Error contacting TSP server " + clockDriftConfig.getServer());
    }

    TimeStampResponse tspResponse = new TimeStampResponse(postMethod.getResponseBodyAsStream());
    postMethod.releaseConnection();

    return tspResponse.getTimeStampToken().getTimeStampInfo().getGenTime();
}

From source file:com.javector.soaj.provider.generatedwsdl.TestProviderGeneratedWsdl.java

public void testProvider() throws Exception {
    SoajProviderService service = new SoajProviderService();
    SoajProviderPortType port = service.getSoajProviderPort();
    Item item = new Item();
    item.setPrice(3.99);/*from   w  w w  . ja v a 2 s.  c  o m*/
    item.setProductName("Diet Coke");
    item.setQuantity(BigInteger.valueOf(6));
    Items items = new Items();
    items.getItem().add(item);
    BillToType billTo = new BillToType();
    billTo.setCity("Canton");
    billTo.setPhone("(973) 243-8776");
    billTo.setState("OH");
    billTo.setStreet("125 Main Street");
    billTo.setZip("98134");
    PurchaseOrder po = new PurchaseOrder();
    po.setBillTo(billTo);
    po.setItems(items);
    BillToType response;
    try {
        response = port.getBillTo(po);
    } catch (SOAPFaultException sfe) {
        SOAPFault sf = sfe.getFault();
        System.out.println("SOAPFault:" + IOUtil.NL + XmlUtil.toFormattedString(sf));
        sf.getDetail();
        throw sfe;
    }
    assertNotNull("SOAP Response should not be null.", response);
    System.out.println("bill to city = " + response.getCity());
    assertEquals("Canton", response.getCity());
}