Example usage for java.math BigInteger toByteArray

List of usage examples for java.math BigInteger toByteArray

Introduction

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

Prototype

public byte[] toByteArray() 

Source Link

Document

Returns a byte array containing the two's-complement representation of this BigInteger.

Usage

From source file:cn.iie.haiep.hbase.value.Bytes.java

/**
 * Iterate over keys within the passed inclusive range.
 *//*w  ww  .j a v a 2 s. co  m*/
public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, final int num) {
    byte[] aPadded;
    byte[] bPadded;
    if (a.length < b.length) {
        aPadded = padTail(a, b.length - a.length);
        bPadded = b;
    } else if (b.length < a.length) {
        aPadded = a;
        bPadded = padTail(b, a.length - b.length);
    } else {
        aPadded = a;
        bPadded = b;
    }
    if (compareTo(aPadded, bPadded) >= 0) {
        throw new IllegalArgumentException("b <= a");
    }
    if (num <= 0) {
        throw new IllegalArgumentException("num cannot be < 0");
    }
    byte[] prependHeader = { 1, 0 };
    final BigInteger startBI = new BigInteger(add(prependHeader, aPadded));
    final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded));
    final BigInteger diffBI = stopBI.subtract(startBI);
    final BigInteger splitsBI = BigInteger.valueOf(num + 1);
    if (diffBI.compareTo(splitsBI) < 0) {
        return null;
    }
    final BigInteger intervalBI;
    try {
        intervalBI = diffBI.divide(splitsBI);
    } catch (Exception e) {
        LOG.error("Exception caught during division", e);
        return null;
    }

    final Iterator<byte[]> iterator = new Iterator<byte[]>() {
        private int i = -1;

        @Override
        public boolean hasNext() {
            return i < num + 1;
        }

        @Override
        public byte[] next() {
            i++;
            if (i == 0)
                return a;
            if (i == num + 1)
                return b;

            BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i)));
            byte[] padded = curBI.toByteArray();
            if (padded[1] == 0)
                padded = tail(padded, padded.length - 2);
            else
                padded = tail(padded, padded.length - 1);
            return padded;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }

    };

    return new Iterable<byte[]>() {
        @Override
        public Iterator<byte[]> iterator() {
            return iterator;
        }
    };
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testPSSPrefix() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//from w  w  w . j  a  v  a2  s.  c  o  m
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PublicKey authnPublicKey = authnCertificate.getPublicKey();

    Signature signature = Signature.getInstance("SHA1withRSAandMGF1");
    signature.initSign(authnPrivateKey);

    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);

    RSAPublicKey rsaPublicKey = (RSAPublicKey) authnPublicKey;
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(),
            rsaPublicKey.getModulus());
    String paddedMessage = new String(Hex.encodeHex(messageBigInteger.toByteArray()));
    LOG.debug("padded message: " + paddedMessage);
    assertTrue(paddedMessage.endsWith("bc"));
}

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

private boolean stepFour() {
    boolean resultFound = false;

    if (this.m.length == 1 && this.m[0].lower.compareTo(this.m[0].upper) == 0) {
        BigInteger solution = this.s0.modInverse(this.pubKey.getModulus());
        solution = solution.multiply(this.m[0].upper).mod(this.pubKey.getModulus());

        publish(solution);// w w w .j ava  2  s.com

        this.result = solution.toByteArray();
        loggerInstance.log(getClass(), "====> Solution found!\n" + solution, Logger.LogLevel.INFO);

        resultFound = true;
    }

    return resultFound;
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

private void verifySignatureAlgorithm(final String signatureAlgorithm, final PrivateKey privateKey,
        final PublicKey publicKey) throws Exception {
    Signature signature = Signature.getInstance(signatureAlgorithm);
    signature.initSign(privateKey);//from  w ww  .  j  a v a 2  s  . c o  m
    assertTrue(signature.getProvider() instanceof BeIDProvider);

    final byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    final byte[] signatureValue = signature.sign();
    assertNotNull(signatureValue);

    signature.initVerify(publicKey);
    signature.update(toBeSigned);
    final boolean beIDResult = signature.verify(signatureValue);
    assertTrue(beIDResult);

    signature = Signature.getInstance(signatureAlgorithm);
    signature.initVerify(publicKey);
    signature.update(toBeSigned);
    final boolean result = signature.verify(signatureValue);
    assertTrue(result);

    RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(),
            rsaPublicKey.getModulus());
    LOG.debug("Padded DigestInfo: " + new String(Hex.encodeHex(messageBigInteger.toByteArray())));
}

From source file:cloud.google.com.windows.example.ExampleCode.java

@SuppressWarnings("unchecked")
private JSONObject jsonEncode(KeyPair keys) throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory factory = KeyFactory.getInstance("RSA");

    // Get the RSA spec for key manipulation.
    RSAPublicKeySpec pubSpec = factory.getKeySpec(keys.getPublic(), RSAPublicKeySpec.class);

    // Extract required parts of the key.
    BigInteger modulus = pubSpec.getModulus();
    BigInteger exponent = pubSpec.getPublicExponent();

    // Grab an encoder for the modulus and exponent to encode using RFC 3548;
    // Java SE 7 requires an external library (Google's Guava used here)
    // Java SE 8 has a built-in Base64 class that can be used instead. Apache also has an RFC 3548
    // encoder./*from w  ww .  ja  va2 s.  c  o  m*/
    BaseEncoding stringEncoder = BaseEncoding.base64();

    // Strip out the leading 0 byte in the modulus.
    byte[] arr = Arrays.copyOfRange(modulus.toByteArray(), 1, modulus.toByteArray().length);

    JSONObject returnJson = new JSONObject();

    // Encode the modulus, add to returned JSON object.
    String modulusString = stringEncoder.encode(arr).replaceAll("\n", "");
    returnJson.put("modulus", modulusString);

    // Encode exponent, add to returned JSON object.
    String exponentString = stringEncoder.encode(exponent.toByteArray()).replaceAll("\n", "");
    returnJson.put("exponent", exponentString);

    return returnJson;
}

From source file:org.viafirma.nucleo.validacion.OcspValidatorHandler.java

/**
 * Genera una nueva peticin OCSP para el certificado indicado.
 * //from   w w w.  jav  a2 s  .c o m
 * @param certificadoX509
 *            Certificado que deseamos validar.
 * @param certificadoX509Emisor
 *            Certificado emisor del certificado a validar.
 * @return Peticin OCSP
 * @throws OCSPException
 */
private OCSPReq generateRequest(X509Certificate certificadoX509, X509Certificate certificadoX509Emisor)
        throws OCSPException {
    // 1 -Generamos el identificador
    CertificateID id = new CertificateID(CertificateID.HASH_SHA1, certificadoX509Emisor,
            certificadoX509.getSerialNumber());

    // 2- Generador de peticiones ocsp
    OCSPReqGenerator requestGenerator = new OCSPReqGenerator();
    requestGenerator.addRequest(id);

    // 3- extensiones necesarias. RFC 2560
    BigInteger time = BigInteger.valueOf(System.currentTimeMillis());
    Vector<DERObjectIdentifier> oids = new Vector<DERObjectIdentifier>();
    oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
    Vector<X509Extension> values = new Vector<X509Extension>();
    values.add(new X509Extension(false, new DEROctetString(time.toByteArray())));

    // 4. Aadimos las extensiones necesarias al generador
    requestGenerator.setRequestExtensions(new X509Extensions(oids, values));

    // Generamos la peticin OCSP
    return requestGenerator.generate();
}

From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java

/**
 * Gets the OCSP status for the specified subject and issuer certificates.
 *
 * @param ocspStatusKey status key//from ww  w  . j a v a 2  s.c o m
 * @return ocsp status
 */
private OcspStatus getOcspStatus(final OcspRequest ocspStatusKey) {
    final X509Certificate subjectCertificate = ocspStatusKey.getSubjectCertificate();
    final X509Certificate issuerCertificate = ocspStatusKey.getIssuerCertificate();

    // initialize the default status
    final OcspStatus ocspStatus = new OcspStatus();
    ocspStatus.setVerificationStatus(VerificationStatus.Unknown);
    ocspStatus.setValidationStatus(ValidationStatus.Unknown);

    try {
        // prepare the request
        final BigInteger subjectSerialNumber = subjectCertificate.getSerialNumber();
        final DigestCalculatorProvider calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                .setProvider("BC").build();
        final CertificateID certificateId = new CertificateID(
                calculatorProviderBuilder.get(CertificateID.HASH_SHA1),
                new X509CertificateHolder(issuerCertificate.getEncoded()), subjectSerialNumber);

        // generate the request
        final OCSPReqBuilder requestGenerator = new OCSPReqBuilder();
        requestGenerator.addRequest(certificateId);

        // Create a nonce to avoid replay attack
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true,
                new DEROctetString(nonce.toByteArray()));
        requestGenerator.setRequestExtensions(new Extensions(new Extension[] { ext }));

        final OCSPReq ocspRequest = requestGenerator.build();

        // perform the request
        final ClientResponse response = getClientResponse(ocspRequest);

        // ensure the request was completed successfully
        if (ClientResponse.Status.OK.getStatusCode() != response.getStatusInfo().getStatusCode()) {
            logger.warn(String.format("OCSP request was unsuccessful (%s).", response.getStatus()));
            return ocspStatus;
        }

        // interpret the response
        OCSPResp ocspResponse = new OCSPResp(response.getEntityInputStream());

        // verify the response status
        switch (ocspResponse.getStatus()) {
        case OCSPRespBuilder.SUCCESSFUL:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Successful);
            break;
        case OCSPRespBuilder.INTERNAL_ERROR:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.InternalError);
            break;
        case OCSPRespBuilder.MALFORMED_REQUEST:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.MalformedRequest);
            break;
        case OCSPRespBuilder.SIG_REQUIRED:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.SignatureRequired);
            break;
        case OCSPRespBuilder.TRY_LATER:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.TryLater);
            break;
        case OCSPRespBuilder.UNAUTHORIZED:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unauthorized);
            break;
        default:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unknown);
            break;
        }

        // only proceed if the response was successful
        if (ocspResponse.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
            logger.warn(String.format("OCSP request was unsuccessful (%s).",
                    ocspStatus.getResponseStatus().toString()));
            return ocspStatus;
        }

        // ensure the appropriate response object
        final Object ocspResponseObject = ocspResponse.getResponseObject();
        if (ocspResponseObject == null || !(ocspResponseObject instanceof BasicOCSPResp)) {
            logger.warn(String.format("Unexpected OCSP response object: %s", ocspResponseObject));
            return ocspStatus;
        }

        // get the response object
        final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) ocspResponse.getResponseObject();

        // attempt to locate the responder certificate
        final X509CertificateHolder[] responderCertificates = basicOcspResponse.getCerts();
        if (responderCertificates.length != 1) {
            logger.warn(String.format("Unexpected number of OCSP responder certificates: %s",
                    responderCertificates.length));
            return ocspStatus;
        }

        // get the responder certificate
        final X509Certificate trustedResponderCertificate = getTrustedResponderCertificate(
                responderCertificates[0], issuerCertificate);
        if (trustedResponderCertificate != null) {
            // verify the response
            if (basicOcspResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC")
                    .build(trustedResponderCertificate.getPublicKey()))) {
                ocspStatus.setVerificationStatus(VerificationStatus.Verified);
            } else {
                ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
            }
        } else {
            ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
        }

        // validate the response
        final SingleResp[] responses = basicOcspResponse.getResponses();
        for (SingleResp singleResponse : responses) {
            final CertificateID responseCertificateId = singleResponse.getCertID();
            final BigInteger responseSerialNumber = responseCertificateId.getSerialNumber();

            if (responseSerialNumber.equals(subjectSerialNumber)) {
                Object certStatus = singleResponse.getCertStatus();

                // interpret the certificate status
                if (CertificateStatus.GOOD == certStatus) {
                    ocspStatus.setValidationStatus(ValidationStatus.Good);
                } else if (certStatus instanceof RevokedStatus) {
                    ocspStatus.setValidationStatus(ValidationStatus.Revoked);
                } else {
                    ocspStatus.setValidationStatus(ValidationStatus.Unknown);
                }
            }
        }
    } catch (final OCSPException | IOException | UniformInterfaceException | ClientHandlerException
            | OperatorCreationException e) {
        logger.error(e.getMessage(), e);
    } catch (CertificateException e) {
        e.printStackTrace();
    }

    return ocspStatus;
}

From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransactionTest.java

@Test
public void testTransactionIsolation() throws Exception {
    // This test creates multiple partially-done transactions and ensures that even after writes
    // and commits, the value returned by get() is consistent with either the initial value or
    // the most recently written value within the transaction.
    int numColumns = 10;
    int numTransactions = 500;

    Transaction initTransaction = txManager.createNewTransaction();
    for (int i = 0; i < numColumns; i++) {
        Cell cell = Cell.create("row".getBytes(), ("column" + i).getBytes());
        BigInteger cellValue = BigInteger.valueOf(i);
        initTransaction.put(TABLE, ImmutableMap.of(cell, cellValue.toByteArray()));
    }//from w  ww . j a va 2  s  .c om
    initTransaction.commit();

    List<Transaction> allTransactions = Lists.newArrayList();
    List<List<BigInteger>> writtenValues = Lists.newArrayList();
    for (int i = 0; i < numTransactions; i++) {
        allTransactions.add(txManager.createNewTransaction());
        List<BigInteger> initialValues = Lists.newArrayList();
        for (int j = 0; j < numColumns; j++) {
            initialValues.add(BigInteger.valueOf(j));
        }
        writtenValues.add(initialValues);
    }

    Random random = new Random(1);
    for (int i = 0; i < 10000 && !allTransactions.isEmpty(); i++) {
        int transactionIndex = random.nextInt(allTransactions.size());
        Transaction t = allTransactions.get(transactionIndex);

        int actionCode = random.nextInt(30);

        if (actionCode == 0) {
            // Commit the transaction and remove it.
            try {
                t.commit();
            } catch (TransactionConflictException e) {
                // Ignore any conflicts; the transaction just fails
            }
            allTransactions.remove(transactionIndex);
            writtenValues.remove(transactionIndex);
        } else if (actionCode < 15) {
            // Write a new value to a random column
            int columnNumber = random.nextInt(numColumns);
            Cell cell = Cell.create("row".getBytes(), ("column" + columnNumber).getBytes());

            BigInteger newValue = BigInteger.valueOf(random.nextInt(100000));
            t.put(TABLE, ImmutableMap.of(cell, newValue.toByteArray()));
            writtenValues.get(transactionIndex).set(columnNumber, newValue);
        } else {
            // Read and verify the value of a random column
            int columnNumber = random.nextInt(numColumns);
            Cell cell = Cell.create("row".getBytes(), ("column" + columnNumber).getBytes());
            byte[] storedValue = t.get(TABLE, Collections.singleton(cell)).get(cell);
            BigInteger expectedValue = writtenValues.get(transactionIndex).get(columnNumber);
            assertEquals(expectedValue, new BigInteger(storedValue));
        }
    }
}

From source file:org.cloudgraph.hbase.service.HBaseDataConverter.java

/**
 * Converts the given value to bytes based on data type and cardinality
 * information for the given property. For 'many' or multi-valued properties,
 * if the SDO Java type for the property is not already String, the value is
 * first converted to String using the SDO conversion which uses
 * java.util.Arrays formatting. For non 'many' or singular properties, only
 * the HBase Bytes utility is used.//  w  w  w .java2s  . c  o m
 * 
 * @param sourceProperty
 *          the source property
 * @param value
 *          the value
 * @return the bytes
 * @throws IllegalArgumentException
 *           if the given property is not a data type property
 */
public byte[] toBytes(Property sourceProperty, Object value) {
    byte[] result;

    if (!sourceProperty.getType().isDataType())
        throw new IllegalArgumentException(
                "property " + sourceProperty.toString() + " is not a datatype property");
    DataType dataType = DataType.valueOf(sourceProperty.getType().getName());

    switch (dataType) {
    // Data types stored as String bytes in HBase
    case String:
    case Strings:
    case URI:
    case Month:
    case MonthDay:
    case Day:
    case Time:
    case Year:
    case YearMonth:
    case YearMonthDay:
    case Date:
    case Duration:
        String resultStr = DataConverter.INSTANCE.toString(sourceProperty, value);
        result = Bytes.toBytes(resultStr);
        break;
    case DateTime:
        resultStr = DataConverter.INSTANCE.toString(sourceProperty, value);
        result = Bytes.toBytes(resultStr);
        break;
    // Data types stored by directly converting from primitive types to
    // bytes in HBase.
    // FIXME: When the given property is a 'many' property and has a variable
    // length, the value is first
    // converted to String so
    // can be delimited.
    case Decimal:
        if (!sourceProperty.isMany()) {
            BigDecimal resultDecimal = DataConverter.INSTANCE.toDecimal(sourceProperty.getType(), value);
            result = Bytes.toBytes(resultDecimal);
        } else {
            String strResult = DataConverter.INSTANCE.toString(sourceProperty, value);
            result = Bytes.toBytes(strResult);
        }
        break;
    case Bytes:
        if (!sourceProperty.isMany()) {
            byte[] resultBytes = DataConverter.INSTANCE.toBytes(sourceProperty.getType(), value);
            result = resultBytes;
        } else {
            String strResult = DataConverter.INSTANCE.toString(sourceProperty, value);
            result = Bytes.toBytes(strResult);
        }
        break;
    case Byte:
        if (!sourceProperty.isMany()) {
            byte resultByte = DataConverter.INSTANCE.toByte(sourceProperty.getType(), value);
            result = Bytes.toBytes(resultByte);
        } else {
            result = (byte[]) value;
        }
        break;
    case Boolean:
        if (!sourceProperty.isMany()) {
            boolean resultBool = DataConverter.INSTANCE.toBoolean(sourceProperty.getType(), value);
            result = Bytes.toBytes(resultBool);
        } else {
            @SuppressWarnings("unchecked")
            List<Boolean> list = (List<Boolean>) value;
            result = new byte[list.size() * Bytes.SIZEOF_BOOLEAN];
            int pos = 0;
            for (Boolean val : list) {
                byte[] bytesVal = Bytes.toBytes(val);
                System.arraycopy(bytesVal, 0, result, pos, Bytes.SIZEOF_BOOLEAN);
                pos += Bytes.SIZEOF_BOOLEAN;
            }
        }
        break;
    case Character:
        if (!sourceProperty.isMany()) {
            resultStr = DataConverter.INSTANCE.toString(sourceProperty.getType(), value);
            result = Bytes.toBytes(resultStr);
        } else {
            String strResult = DataConverter.INSTANCE.toString(sourceProperty, value);
            result = Bytes.toBytes(strResult);
        }
        break;
    case Double:
        if (!sourceProperty.isMany()) {
            double resultDouble = DataConverter.INSTANCE.toDouble(sourceProperty.getType(), value);
            result = Bytes.toBytes(resultDouble);
        } else {
            @SuppressWarnings("unchecked")
            List<Double> list = (List<Double>) value;
            result = new byte[list.size() * Bytes.SIZEOF_LONG];
            int pos = 0;
            for (Double val : list) {
                byte[] bytesVal = Bytes.toBytes(val);
                System.arraycopy(bytesVal, 0, result, pos, Bytes.SIZEOF_LONG);
                pos += Bytes.SIZEOF_LONG;
            }
        }
        break;
    case Float:
        if (!sourceProperty.isMany()) {
            float resultFloat = DataConverter.INSTANCE.toFloat(sourceProperty.getType(), value);
            result = Bytes.toBytes(resultFloat);
        } else {
            @SuppressWarnings("unchecked")
            List<Float> list = (List<Float>) value;
            result = new byte[list.size() * Bytes.SIZEOF_INT];
            int pos = 0;
            for (Float val : list) {
                byte[] bytesVal = Bytes.toBytes(val);
                System.arraycopy(bytesVal, 0, result, pos, Bytes.SIZEOF_INT);
                pos += Bytes.SIZEOF_INT;
            }
        }
        break;
    case Int:
        if (!sourceProperty.isMany()) {
            int resultInt = DataConverter.INSTANCE.toInt(sourceProperty.getType(), value);
            result = Bytes.toBytes(resultInt);
        } else {
            @SuppressWarnings("unchecked")
            List<Integer> list = (List<Integer>) value;
            result = new byte[list.size() * Bytes.SIZEOF_INT];
            int pos = 0;
            for (Integer val : list) {
                byte[] bytesVal = Bytes.toBytes(val);
                System.arraycopy(bytesVal, 0, result, pos, Bytes.SIZEOF_INT);
                pos += Bytes.SIZEOF_INT;
            }
        }
        break;
    case UnsignedInt:
        if (!sourceProperty.isMany()) {
            UnsignedInteger resultInt = DataConverter.INSTANCE.toUnsignedInt(sourceProperty.getType(), value);
            result = Ints.toByteArray(resultInt.intValue());

        } else {
            @SuppressWarnings("unchecked")
            List<UnsignedInteger> list = (List<UnsignedInteger>) value;
            result = new byte[list.size() * Bytes.SIZEOF_INT];
            int pos = 0;
            for (UnsignedInteger val : list) {
                byte[] bytesVal = Ints.toByteArray(val.intValue());
                System.arraycopy(bytesVal, 0, result, pos, Bytes.SIZEOF_INT);
                pos += Bytes.SIZEOF_INT;
            }
        }
        break;
    case Integer:
        if (!sourceProperty.isMany()) {
            BigInteger resultInteger = DataConverter.INSTANCE.toInteger(sourceProperty.getType(), value);
            result = resultInteger.toByteArray();
        } else {
            String strResult = DataConverter.INSTANCE.toString(sourceProperty, value);
            result = Bytes.toBytes(strResult);
        }
        break;
    case Long:
        if (!sourceProperty.isMany()) {
            long resultLong = DataConverter.INSTANCE.toLong(sourceProperty.getType(), value);
            result = Bytes.toBytes(resultLong);
        } else {
            @SuppressWarnings("unchecked")
            List<Long> list = (List<Long>) value;
            result = new byte[list.size() * Bytes.SIZEOF_LONG];
            int pos = 0;
            for (Long val : list) {
                byte[] bytesVal = Bytes.toBytes(val);
                System.arraycopy(bytesVal, 0, result, pos, Bytes.SIZEOF_LONG);
                pos += Bytes.SIZEOF_LONG;
            }
        }
        break;
    case UnsignedLong:
        if (!sourceProperty.isMany()) {
            UnsignedLong resultInt = DataConverter.INSTANCE.toUnsignedLong(sourceProperty.getType(), value);
            result = Longs.toByteArray(resultInt.longValue());
        } else {
            @SuppressWarnings("unchecked")
            List<UnsignedLong> list = (List<UnsignedLong>) value;
            result = new byte[list.size() * Bytes.SIZEOF_LONG];
            int pos = 0;
            for (UnsignedLong val : list) {
                byte[] bytesVal = Longs.toByteArray(val.longValue());
                System.arraycopy(bytesVal, 0, result, pos, Bytes.SIZEOF_LONG);
                pos += Bytes.SIZEOF_LONG;
            }
        }
        break;
    case Short:
        if (!sourceProperty.isMany()) {
            short resultShort = DataConverter.INSTANCE.toShort(sourceProperty.getType(), value);
            result = Bytes.toBytes(resultShort);
        } else {
            @SuppressWarnings("unchecked")
            List<Short> list = (List<Short>) value;
            result = new byte[list.size() * Bytes.SIZEOF_SHORT];
            int pos = 0;
            for (Short val : list) {
                byte[] bytesVal = Bytes.toBytes(val);
                System.arraycopy(bytesVal, 0, result, pos, Bytes.SIZEOF_SHORT);
                pos += Bytes.SIZEOF_SHORT;
            }
        }
        break;
    case Object:
        // FIXME: do we serialize objects in some custom format for
        // hbase
    default:
        resultStr = DataConverter.INSTANCE.toString(sourceProperty.getType(), value);
        result = Bytes.toBytes(resultStr);
        break;
    }
    return result;
}

From source file:co.rsk.mine.MinerServerImpl.java

private BlockHeader createHeader(Block newBlockParent, List<BlockHeader> uncles, List<Transaction> txs,
        BigInteger minimumGasPrice) {
    final byte[] unclesListHash = HashUtil.sha3(BlockHeader.getUnclesEncodedEx(uncles));

    final long timestampSeconds = this.getCurrentTimeInSeconds();

    // Set gas limit before executing block
    BigInteger minGasLimit = BigInteger
            .valueOf(properties.getBlockchainConfig().getCommonConstants().getMIN_GAS_LIMIT());
    BigInteger targetGasLimit = BigInteger
            .valueOf(properties.getBlockchainConfig().getCommonConstants().getTARGET_GAS_LIMIT());
    BigInteger parentGasLimit = new BigInteger(1, newBlockParent.getGasLimit());
    BigInteger gasLimit = new GasLimitCalculator().calculateBlockGasLimit(parentGasLimit,
            BigInteger.valueOf(newBlockParent.getGasUsed()), minGasLimit, targetGasLimit);

    final BlockHeader newHeader = new BlockHeader(newBlockParent.getHash(), unclesListHash, coinbaseAddress,
            new Bloom().getData(), new byte[] { 1 }, newBlockParent.getNumber() + 1, gasLimit.toByteArray(), 0,
            timestampSeconds, new byte[] {}, new byte[] {}, new byte[] {}, new byte[] {},
            minimumGasPrice.toByteArray(), CollectionUtils.size(uncles));
    newHeader.setDifficulty(newHeader.calcDifficulty(newBlockParent.getHeader()).toByteArray());
    newHeader.setTransactionsRoot(Block.getTxTrie(txs).getHash());
    return newHeader;
}