Example usage for java.math BigInteger equals

List of usage examples for java.math BigInteger equals

Introduction

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

Prototype

public boolean equals(Object x) 

Source Link

Document

Compares this BigInteger with the specified Object for equality.

Usage

From source file:org.trnltk.numeral.DigitsToTextConverter.java

private String convertNaturalNumberToWords(BigInteger naturalNumber) {
    Validate.isTrue(naturalNumber.compareTo(ZERO) >= 0);
    Validate.isTrue(naturalNumber.compareTo(MAX_NATURAL_NUMBER_SUPPORTED) <= 0, "Given number " + naturalNumber
            + " is larger than maximum supported natural number " + MAX_NATURAL_NUMBER_SUPPORTED);

    StringBuilder result = new StringBuilder();

    if (naturalNumber.compareTo(BigInteger.TEN) < 0) {
        result.append(NUMERAL_SYMBOL_NAMES.get(naturalNumber.intValue()));

    } else if (naturalNumber.compareTo(ONE_HUNDRED) < 0) {
        final BigInteger tensDigit = naturalNumber.divide(TEN);
        final BigInteger onesDigit = naturalNumber.mod(TEN);
        final String strTensDigit = TENS_MULTIPLES_NAMES.get(tensDigit.intValue());
        final String strOnesDigit = onesDigit.compareTo(ZERO) > 0 ? convertNaturalNumberToWords(onesDigit)
                : StringUtils.EMPTY;//www  .j  a  v a  2  s .  c  om
        result.append(strTensDigit).append(" ").append(strOnesDigit);

    } else if (naturalNumber.compareTo(ONE_THOUSAND) < 0) {
        final BigInteger hundredsDigit = naturalNumber.divide(ONE_HUNDRED);
        final BigInteger rest = naturalNumber.mod(ONE_HUNDRED);
        final String strHundredsDigit;
        if (hundredsDigit.equals(ZERO)) {
            strHundredsDigit = StringUtils.EMPTY;
        } else if (hundredsDigit.equals(ONE)) {
            strHundredsDigit = StringUtils.EMPTY;
        } else {
            strHundredsDigit = convertNaturalNumberToWords(hundredsDigit);
        }

        final String restStr = rest.compareTo(ZERO) > 0 ? convertNaturalNumberToWords(rest) : StringUtils.EMPTY;

        result.append(strHundredsDigit).append(" ").append(HUNDRED_NAME).append(" ").append(restStr);

    } else {
        int mostSignificantGroupBase = this.findMostSignificantGroupBase(naturalNumber);
        for (int i = mostSignificantGroupBase / 3; i > 0; i--) {
            int groupNumber = this.getNthGroupNumber(naturalNumber, i);
            //noinspection StatementWithEmptyBody
            if (groupNumber == 0) {
                // don't write 'sifir milyon'
            } else if (groupNumber == 1 && i == 1) {
                // don't write 'bir bin', but write 'bir milyon'(below)
                result.append(" ").append(THOUSAND_NAME);
            } else {
                final String strGroupNumber = this.convertNaturalNumberToWords(BigInteger.valueOf(groupNumber));
                result.append(" ").append(strGroupNumber).append(" ").append(THOUSAND_POWER_NAMES.get(i));
            }

            result = new StringBuilder(result.toString().trim());
        }

        final BigInteger lastGroupNumber = naturalNumber.mod(ONE_THOUSAND);
        if (lastGroupNumber.compareTo(ZERO) > 0)
            result.append(" ").append(convertNaturalNumberToWords(lastGroupNumber));
    }

    return result.toString().trim();
}

From source file:be.fedict.eid.dss.spi.utils.XAdESUtils.java

public static void verifyTimeStampTokenSignature(TimeStampToken timeStampToken)
        throws XAdESValidationException {

    try {//ww w. jav  a2  s.  c o m
        SignerId signerId = timeStampToken.getSID();
        BigInteger signerCertSerialNumber = signerId.getSerialNumber();
        //X500Principal signerCertIssuer = signerId.getIssuer();
        X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded());

        CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection",
                BouncyCastleProvider.PROVIDER_NAME);
        Collection<? extends Certificate> certificates = certStore.getCertificates(null);
        X509Certificate tsaCertificate = null;
        for (Certificate certificate : certificates) {
            X509Certificate x509Certificate = (X509Certificate) certificate;
            if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal())
                    && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
                tsaCertificate = x509Certificate;
                break;
            }
        }

        if (null == tsaCertificate) {
            throw new XAdESValidationException("TSA certificate not present in TST");
        }

        timeStampToken.validate(tsaCertificate, BouncyCastleProvider.PROVIDER_NAME);
    } catch (Exception e) {
        throw new XAdESValidationException(e);
    }
}

From source file:chibi.gemmaanalysis.SummaryStatistics.java

/**
 * For each pair of genes, count how many expression experiments both appear in.
 * //from  ww w . j a  v  a  2  s  . c om
 * @param taxon
 */
public void genePairOccurrenceDistributions(Taxon taxon) {

    Collection<ExpressionExperiment> eeColl = expressionExperimentService.loadAll();

    CompressedSparseDoubleMatrix<Long, Long> mat = new CompressedSparseDoubleMatrix<Long, Long>(MAX_GENES,
            MAX_GENES);

    int numEEs = 0;
    for (ExpressionExperiment experiment : eeColl) {
        if (numEEs > MAX_EXPS)
            break;
        Taxon eeTax = expressionExperimentService.getTaxon(experiment);
        if (eeTax == null || !eeTax.equals(taxon))
            continue;
        Collection<ArrayDesign> ads = expressionExperimentService.getArrayDesignsUsed(experiment);

        // only count each gene once per data set.
        Collection<Long> seenids = new HashSet<Long>();

        for (ArrayDesign design : ads) {

            Collection<Object[]> vals = compositeSequenceService.getRawSummary(design, null);
            log.info(numEEs + " " + design + "Got " + vals.size() + " reports");

            for (Object[] objects : vals) {

                BigInteger geneidi = (BigInteger) objects[10];
                if (geneidi == null) {
                    continue;
                }
                Long geneid = geneidi.longValue();

                if (seenids.contains(geneid))
                    continue;

                if (!mat.containsRowName(geneid)) {
                    mat.addRowName(geneid);
                }

                int outerIndex = mat.getRowIndexByName(geneid);

                int j = 0;
                for (Object[] ojbB : vals) {

                    BigInteger geneBidi = (BigInteger) ojbB[10];
                    if (geneBidi == null || geneBidi.equals(geneidi)) {
                        continue;
                    }
                    Long geneBid = geneBidi.longValue();
                    if (seenids.contains(geneBid))
                        continue;
                    int innerIndex;
                    if (!mat.containsColumnName(geneBid)) {
                        mat.addColumnName(geneBid);
                        innerIndex = mat.getColIndexByName(geneBid);
                        mat.set(outerIndex, innerIndex, 0.0); // initialize
                    }

                    innerIndex = mat.getColIndexByName(geneBid);
                    mat.set(outerIndex, innerIndex, mat.get(outerIndex, innerIndex) + 1);

                    if (mat.columns() > MAX_GENES) {
                        log.warn("Too many genes!");
                        break;
                    }
                    j++;
                    if (j > 1000)
                        break;
                }
                seenids.add(geneid);

                if (mat.rows() > MAX_GENES) {
                    break;
                }

            }

        }
        numEEs++;
    }

    // print the histogram.
    int[] counts = new int[MAX_EXPS + 1];
    for (Long outer : mat.getRowNames()) {
        double[] row = mat.getRowByName(outer);
        for (double d : row) {
            counts[(int) d]++;
        }
    }

    for (int j = 0; j < counts.length; j++) {
        System.out.println(j + "\t" + counts[j]);
    }
}

From source file:org.opendaylight.netvirt.ipv6service.utils.Ipv6ServiceUtils.java

public void installIcmpv6RsPuntFlow(short tableId, BigInteger dpId, Long elanTag, IMdsalApiManager mdsalUtil,
        int addOrRemove) {
    if (dpId == null || dpId.equals(Ipv6Constants.INVALID_DPID)) {
        return;/*from  w  ww  .  j  a v a 2 s .  c  o m*/
    }
    List<MatchInfo> routerSolicitationMatch = getIcmpv6RSMatch(elanTag);
    List<InstructionInfo> instructions = new ArrayList<>();
    List<ActionInfo> actionsInfos = new ArrayList<>();
    // Punt to controller
    actionsInfos.add(new ActionPuntToController());
    instructions.add(new InstructionApplyActions(actionsInfos));
    FlowEntity rsFlowEntity = MDSALUtil.buildFlowEntity(dpId, tableId, getIPv6FlowRef(dpId, elanTag, "IPv6RS"),
            Ipv6Constants.DEFAULT_FLOW_PRIORITY, "IPv6RS", 0, 0, NwConstants.COOKIE_IPV6_TABLE,
            routerSolicitationMatch, instructions);
    if (addOrRemove == Ipv6Constants.DEL_FLOW) {
        LOG.trace("Removing IPv6 Router Solicitation Flow DpId {}, elanTag {}", dpId, elanTag);
        mdsalUtil.removeFlow(rsFlowEntity);
    } else {
        LOG.trace("Installing IPv6 Router Solicitation Flow DpId {}, elanTag {}", dpId, elanTag);
        mdsalUtil.installFlow(rsFlowEntity);
    }
}

From source file:org.opendaylight.genius.itm.impl.ItmUtils.java

public static List<DPNTEPsInfo> getDpnTepListFromDpnId(DataBroker dataBroker, List<BigInteger> dpnIds) {
    List<DPNTEPsInfo> meshedDpnList = getTunnelMeshInfo(dataBroker);
    List<DPNTEPsInfo> cfgDpnList = new ArrayList<>();
    if (null != meshedDpnList) {
        for (BigInteger dpnId : dpnIds) {
            for (DPNTEPsInfo teps : meshedDpnList) {
                if (dpnId.equals(teps.getDPNID())) {
                    cfgDpnList.add(teps);
                }//  ww w  .  j ava 2  s. com
            }
        }
    }
    return cfgDpnList;
}

From source file:eu.europa.esig.dss.pades.InfiniteLoopDSS621Test.java

/**
 * These signatures are invalid because of non ordered  signed attributes
 *///from   ww w  .j  a va2  s  . c o  m
@Test
public void manualTest() throws Exception {

    File pdfFile = new File(FILE_PATH);

    FileInputStream fis = new FileInputStream(pdfFile);
    byte[] pdfBytes = IOUtils.toByteArray(fis);

    PDDocument document = PDDocument.load(pdfFile);
    List<PDSignature> signatures = document.getSignatureDictionaries();
    assertEquals(6, signatures.size());

    int idx = 0;
    for (PDSignature pdSignature : signatures) {
        byte[] contents = pdSignature.getContents(pdfBytes);
        byte[] signedContent = pdSignature.getSignedContent(pdfBytes);

        logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange()));

        IOUtils.write(contents, new FileOutputStream("target/sig" + (idx++) + ".p7s"));

        ASN1InputStream asn1sInput = new ASN1InputStream(contents);
        ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

        logger.info("SEQ : " + asn1Seq.toString());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);

        SignedData signedData = SignedData
                .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject());

        ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms();
        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier
                .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0));
        DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId());
        logger.info("DIGEST ALGO : " + digestAlgorithm);

        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType();
        logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID);

        if (!PKCSObjectIdentifiers.id_ct_TSTInfo.equals(contentTypeOID)) { // If not timestamp
            assertEquals(PKCSObjectIdentifiers.data, contentTypeOID);

            ASN1Encodable content = encapContentInfo.getContent();
            logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content);
            assertNull(content);

            List<X509Certificate> certificates = extractCertificates(signedData);

            ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
            logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
            SignerInfo signedInfo = SignerInfo
                    .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

            ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes();
            logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet);

            Attribute attributeDigest = null;
            for (int i = 0; i < authenticatedAttributeSet.size(); i++) {
                Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i));
                if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attribute.getAttrType())) {
                    attributeDigest = attribute;
                    break;
                }
            }

            assertNotNull(attributeDigest);

            ASN1OctetString asn1ObjString = ASN1OctetString
                    .getInstance(attributeDigest.getAttrValues().getObjectAt(0));
            String embeddedDigest = Base64.encode(asn1ObjString.getOctets());
            logger.info("MESSAGE DIGEST : " + embeddedDigest);

            byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
            String computedDigestSignedContentEncodeBase64 = Base64.encode(digestSignedContent);
            logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64);
            assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64);

            SignerIdentifier sid = signedInfo.getSID();
            logger.info("SIGNER IDENTIFIER : " + sid.getId());

            IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber
                    .getInstance(signedInfo.getSID());
            ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber();
            logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber);

            BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();
            X509Certificate signerCertificate = null;
            for (X509Certificate x509Certificate : certificates) {
                if (serial.equals(x509Certificate.getSerialNumber())) {
                    signerCertificate = x509Certificate;
                }
            }
            assertNotNull(signerCertificate);

            String algorithm = signerCertificate.getPublicKey().getAlgorithm();
            EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm);

            ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
            String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

            logger.info("SIGNATURE VALUE : " + signatureValue);

            Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName());
            cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
            byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

            ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

            ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
            logger.info("DECRYPTED : " + seqDecrypt);

            DigestInfo digestInfo = new DigestInfo(seqDecrypt);
            assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

            String decryptedDigestEncodeBase64 = Base64.encode(digestInfo.getDigest());
            logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

            byte[] encoded = authenticatedAttributeSet.getEncoded();
            byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
            String computedDigestFromSignatureEncodeBase64 = Base64.encode(digest);
            logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64);

            assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64);

            IOUtils.closeQuietly(inputDecrypted);

        }

        IOUtils.closeQuietly(asn1sInput);
    }

    IOUtils.closeQuietly(fis);
    document.close();
}

From source file:org.eclipse.om2m.binding.http.RestHttpClient.java

/**
 * Converts a protocol-independent {@link RequestPrimitive} object into a standard HTTP request and sends a standard HTTP request.
 * Converts the received standard HTTP request into {@link ResponsePrimitive} object and returns it back.
 * @param requestPrimitive - protocol independent request.
 * @return protocol independent response.
 *///from   www  .j  av  a  2  s.  com
public ResponsePrimitive sendRequest(RequestPrimitive requestPrimitive) {
    LOGGER.info("Sending request: " + requestPrimitive);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    ResponsePrimitive responsePrimitive = new ResponsePrimitive(requestPrimitive);
    HttpUriRequest method = null;

    // Retrieve the url
    String url = requestPrimitive.getTo();
    if (!url.startsWith(protocol + "://")) {
        if (url.startsWith("://")) {
            url = protocol + url;
        } else if (url.startsWith("//")) {
            url = protocol + ":" + url;
        } else {
            url = protocol + "://" + url;
        }
    }

    Map<String, List<String>> parameters = getParameters(requestPrimitive);
    parameters.putAll(requestPrimitive.getQueryStrings());
    if (!parameters.isEmpty()) {
        String queryString = "";
        for (String parameter : parameters.keySet()) {
            for (String value : parameters.get(parameter)) {
                queryString += "&" + parameter + "=" + value;
            }
        }
        queryString = queryString.replaceFirst("&", "?");
        LOGGER.info("Query string generated: " + queryString);
        url += queryString;
    }

    try {
        // Set the operation
        BigInteger operation = requestPrimitive.getOperation();
        if (operation != null) {
            if (operation.equals(Operation.CREATE)) {
                method = new HttpPost(url);
                if (requestPrimitive.getContent() != null) {
                    ((HttpPost) method).setEntity(new StringEntity((String) requestPrimitive.getContent()));
                }
            } else if (operation.equals(Operation.RETRIEVE)) {
                method = new HttpGet(url);
            } else if (operation.equals(Operation.UPDATE)) {
                method = new HttpPut(url);
                if (requestPrimitive.getContent() != null) {
                    ((HttpPut) method).setEntity(new StringEntity((String) requestPrimitive.getContent()));
                }
            } else if (operation.equals(Operation.DELETE)) {
                method = new HttpDelete(url);
            } else if (operation.equals(Operation.NOTIFY)) {
                method = new HttpPost(url);
                if (requestPrimitive.getContent() != null) {
                    ((HttpPost) method).setEntity(new StringEntity((String) requestPrimitive.getContent()));
                }
            }
        } else {
            return null;
        }

        // Set the return content type
        method.addHeader(HttpHeaders.ACCEPT, requestPrimitive.getReturnContentType());

        // Set the request content type
        String contentTypeHeader = requestPrimitive.getRequestContentType();

        // Set the request identifier header
        if (requestPrimitive.getRequestIdentifier() != null) {
            method.addHeader(HttpHeaders.REQUEST_IDENTIFIER, requestPrimitive.getRequestIdentifier());
        }

        // Set the originator header
        if (requestPrimitive.getFrom() != null) {
            method.addHeader(HttpHeaders.ORIGINATOR, requestPrimitive.getFrom());
        }

        // Add the content type header with the resource type for create operation
        if (requestPrimitive.getResourceType() != null) {
            contentTypeHeader += ";ty=" + requestPrimitive.getResourceType().toString();
        }
        method.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeHeader);

        // Add the notification URI in the case of non-blocking request
        if (requestPrimitive.getResponseTypeInfo() != null) {
            String uris = "";
            for (String notifUri : requestPrimitive.getResponseTypeInfo().getNotificationURI()) {
                uris += "&" + notifUri;
            }
            uris = uris.replaceFirst("&", "");
            method.addHeader(HttpHeaders.RESPONSE_TYPE, uris);
        }

        if (requestPrimitive.getName() != null) {
            method.addHeader(HttpHeaders.NAME, requestPrimitive.getName());
        }

        LOGGER.info("Request to be send: " + method.toString());
        String headers = "";
        for (Header h : method.getAllHeaders()) {
            headers += h.toString() + "\n";
        }
        LOGGER.info("Headers:\n" + headers);

        HttpResponse httpResponse = httpClient.execute(method);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (httpResponse.getFirstHeader(HttpHeaders.RESPONSE_STATUS_CODE) != null) {
            responsePrimitive.setResponseStatusCode(
                    new BigInteger(httpResponse.getFirstHeader(HttpHeaders.RESPONSE_STATUS_CODE).getValue()));
        } else {
            responsePrimitive.setResponseStatusCode(getResponseStatusCode(httpResponse, statusCode));
        }
        if (statusCode != 204) {
            if (httpResponse.getEntity() != null) {
                responsePrimitive.setContent(Util.convertStreamToString(httpResponse.getEntity().getContent()));
                if (httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE) != null) {
                    responsePrimitive
                            .setContentType(httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
                }
            }
        }
        if (statusCode == 201) {
            String contentHeader = "";
            for (Header header : httpResponse.getHeaders(HttpHeaders.CONTENT_LOCATION)) {
                contentHeader += header.getValue();
            }
            responsePrimitive.setLocation(contentHeader);
        }
        LOGGER.info("Http Client response: " + responsePrimitive);
        httpClient.close();
    } catch (HttpHostConnectException e) {
        LOGGER.info("Target is not reachable: " + requestPrimitive.getTo());
        responsePrimitive.setResponseStatusCode(ResponseStatusCode.TARGET_NOT_REACHABLE);
        responsePrimitive.setContent("Target is not reachable: " + requestPrimitive.getTo());
        responsePrimitive.setContentType(MimeMediaType.TEXT_PLAIN);
    } catch (IOException e) {
        LOGGER.error(url + " not found", e);
        responsePrimitive.setResponseStatusCode(ResponseStatusCode.TARGET_NOT_REACHABLE);
    }
    return responsePrimitive;
}

From source file:eu.europa.esig.dss.pades.signature.PAdESLevelBTest.java

@Override
protected void onDocumentSigned(byte[] byteArray) {
    try {/*from   www  .j av  a 2  s  . c om*/
        InputStream inputStream = new ByteArrayInputStream(byteArray);

        PDDocument document = PDDocument.load(inputStream);
        List<PDSignature> signatures = document.getSignatureDictionaries();
        assertEquals(1, signatures.size());

        for (PDSignature pdSignature : signatures) {
            byte[] contents = pdSignature.getContents(byteArray);
            byte[] signedContent = pdSignature.getSignedContent(byteArray);

            logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange()));

            //IOUtils.write(contents, new FileOutputStream("sig.p7s"));

            ASN1InputStream asn1sInput = new ASN1InputStream(contents);
            ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

            logger.info("SEQ : " + asn1Seq.toString());

            ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
            assertEquals(PKCSObjectIdentifiers.signedData, oid);

            SignedData signedData = SignedData
                    .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject());

            ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms();
            ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier
                    .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0));
            DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId());
            logger.info("DIGEST ALGO : " + digestAlgorithm);

            ContentInfo encapContentInfo = signedData.getEncapContentInfo();
            ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType();
            logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID);
            assertEquals(PKCSObjectIdentifiers.data, contentTypeOID);

            ASN1Encodable content = encapContentInfo.getContent();
            logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content);
            assertNull(content);

            List<X509Certificate> certificates = extractCertificates(signedData);

            ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
            logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
            SignerInfo signedInfo = SignerInfo
                    .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

            ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes();
            logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet);

            List<ASN1ObjectIdentifier> attributeOids = new ArrayList<ASN1ObjectIdentifier>();
            for (int i = 0; i < authenticatedAttributeSet.size(); i++) {
                Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i));
                attributeOids.add(attribute.getAttrType());
            }
            logger.info("List of OID for Auth Attrb : " + attributeOids);

            Attribute attributeDigest = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(1));
            assertEquals(PKCSObjectIdentifiers.pkcs_9_at_messageDigest, attributeDigest.getAttrType());

            ASN1OctetString asn1ObjString = ASN1OctetString
                    .getInstance(attributeDigest.getAttrValues().getObjectAt(0));
            String embeddedDigest = Base64.encode(asn1ObjString.getOctets());
            logger.info("MESSAGE DIGEST : " + embeddedDigest);

            byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
            String computedDigestSignedContentEncodeBase64 = Base64.encode(digestSignedContent);
            logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64);
            assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64);

            SignerIdentifier sid = signedInfo.getSID();
            logger.info("SIGNER IDENTIFIER : " + sid.getId());

            IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber
                    .getInstance(signedInfo.getSID());
            ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber();
            logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber);

            BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();
            X509Certificate signerCertificate = null;
            for (X509Certificate x509Certificate : certificates) {
                if (serial.equals(x509Certificate.getSerialNumber())) {
                    signerCertificate = x509Certificate;
                }
            }
            assertNotNull(signerCertificate);

            String algorithm = signerCertificate.getPublicKey().getAlgorithm();
            EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm);

            ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
            String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

            logger.info("SIGNATURE VALUE : " + signatureValue);

            Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName());
            cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
            byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

            ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

            ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
            logger.info("DECRYPTED : " + seqDecrypt);

            DigestInfo digestInfo = new DigestInfo(seqDecrypt);
            assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

            String decryptedDigestEncodeBase64 = Base64.encode(digestInfo.getDigest());
            logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

            byte[] encoded = authenticatedAttributeSet.getEncoded();
            byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
            String computedDigestFromSignatureEncodeBase64 = Base64.encode(digest);
            logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64);

            assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64);

            IOUtils.closeQuietly(inputDecrypted);
            IOUtils.closeQuietly(asn1sInput);
        }

        IOUtils.closeQuietly(inputStream);
        document.close();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    }
}

From source file:eu.stratuslab.storage.disk.resources.DisksResource.java

private void initializeContents(String uuid, Form form) throws ResourceException {

    Map<String, BigInteger> streamInfo = null;

    String url = form.getFirstValue(URL_KEY);
    if (url == null) {
        // If no URL, then bail out; there is nothing to do.
        getLogger().info(String.format("DisksResource NOT initializing contents of %s", uuid));
        return;//from   w  w  w . j  av  a  2  s  .co  m
    }

    getLogger().info(String.format("DisksResource initializing contents of %s from %s", uuid, url));

    try {
        // FIXME: This provides the file information for the download
        // itself. It does NOT actually verify the data on disk. An
        // additional check should probably be added.
        streamInfo = DiskUtils.copyUrlToVolume(uuid, url);
    } catch (IOException e) {
        String msg = "error initializing disk contents from " + url;

        StringWriter sw = null;
        PrintWriter pw = null;
        try {

            sw = new StringWriter();
            pw = new PrintWriter(sw);

            e.printStackTrace(pw);
            getLogger().warning(msg + "\ntraceback:\n" + sw.toString());
        } finally {
            FileUtils.closeIgnoringError(pw);
            FileUtils.closeIgnoringError(sw);
        }

        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, msg);
    }

    String bytes = form.getFirstValue(BYTES_KEY);
    if (bytes != null) {
        BigInteger expected = new BigInteger(bytes);
        BigInteger found = streamInfo.get("BYTES");

        getLogger().info(String.format("DisksResource copied bytes for %s: %s (copied), %s (expected)", uuid,
                found, expected));

        if (!expected.equals(found)) {
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
                    String.format("size mismatch: %s (found) != %s (expected)", found, expected));
        }
    }

    String sha1 = form.getFirstValue(SHA1_KEY);
    if (sha1 != null) {
        try {
            BigInteger expected = new BigInteger(sha1, 16);
            BigInteger found = streamInfo.get("SHA-1");

            getLogger().info(String.format("DisksResource sha1 checksums for %s: %s (copied), %s (expected)",
                    uuid, found, expected));

            if (!expected.equals(found)) {
                throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
                        String.format("checksum mismatch: %s (found) != %s (expected)", found, expected));
            }
        } catch (IllegalArgumentException e) {
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "invalid SHA-1 checksum: " + sha1);
        }
    }

}

From source file:brut.androlib.res.decoder.ARSCDecoder.java

private ResConfigFlags readConfigFlags() throws IOException, AndrolibException {
    int size = mIn.readInt();
    int read = 0;

    if (size < 28) {
        throw new AndrolibException("Config size < 28");
    }// ww w. j a va 2  s .c o  m

    boolean isInvalid = false;

    short mcc = mIn.readShort();
    short mnc = mIn.readShort();

    char[] language = this.unpackLanguageOrRegion(mIn.readByte(), mIn.readByte(), 'a');
    char[] country = this.unpackLanguageOrRegion(mIn.readByte(), mIn.readByte(), '0');

    byte orientation = mIn.readByte();
    byte touchscreen = mIn.readByte();

    int density = mIn.readUnsignedShort();

    byte keyboard = mIn.readByte();
    byte navigation = mIn.readByte();
    byte inputFlags = mIn.readByte();
    /* inputPad0 */mIn.skipBytes(1);

    short screenWidth = mIn.readShort();
    short screenHeight = mIn.readShort();

    short sdkVersion = mIn.readShort();
    /* minorVersion, now must always be 0 */mIn.skipBytes(2);

    byte screenLayout = 0;
    byte uiMode = 0;
    short smallestScreenWidthDp = 0;
    if (size >= 32) {
        screenLayout = mIn.readByte();
        uiMode = mIn.readByte();
        smallestScreenWidthDp = mIn.readShort();
        read = 32;
    }

    short screenWidthDp = 0;
    short screenHeightDp = 0;
    if (size >= 36) {
        screenWidthDp = mIn.readShort();
        screenHeightDp = mIn.readShort();
        read = 36;
    }

    char[] localeScript = null;
    char[] localeVariant = null;
    if (size >= 48) {
        localeScript = readScriptOrVariantChar(4).toCharArray();
        localeVariant = readScriptOrVariantChar(8).toCharArray();
        read = 48;
    }

    byte screenLayout2 = 0;
    if (size >= 52) {
        screenLayout2 = mIn.readByte();
        mIn.skipBytes(3); // reserved padding
        read = 52;
    }

    int exceedingSize = size - KNOWN_CONFIG_BYTES;
    if (exceedingSize > 0) {
        byte[] buf = new byte[exceedingSize];
        read += exceedingSize;
        mIn.readFully(buf);
        BigInteger exceedingBI = new BigInteger(1, buf);

        if (exceedingBI.equals(BigInteger.ZERO)) {
            LOGGER.fine(String.format(
                    "Config flags size > %d, but exceeding bytes are all zero, so it should be ok.",
                    KNOWN_CONFIG_BYTES));
        } else {
            LOGGER.warning(String.format("Config flags size > %d. Exceeding bytes: 0x%X.", KNOWN_CONFIG_BYTES,
                    exceedingBI));
            isInvalid = true;
        }
    }

    int remainingSize = size - read;
    if (remainingSize > 0) {
        mIn.skipBytes(remainingSize);
    }

    return new ResConfigFlags(mcc, mnc, language, country, orientation, touchscreen, density, keyboard,
            navigation, inputFlags, screenWidth, screenHeight, sdkVersion, screenLayout, uiMode,
            smallestScreenWidthDp, screenWidthDp, screenHeightDp, localeScript, localeVariant, screenLayout2,
            isInvalid);
}