Example usage for org.apache.commons.codec.binary Hex encodeHexString

List of usage examples for org.apache.commons.codec.binary Hex encodeHexString

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Hex encodeHexString.

Prototype

public static String encodeHexString(byte[] data) 

Source Link

Document

Converts an array of bytes into a String representing the hexadecimal values of each byte in order.

Usage

From source file:VerifyDescriptors.java

private static String determineKeyHash(String key) throws Exception {
    PEMReader pemReader = new PEMReader(new StringReader(key));
    RSAPublicKey dirIdentityKey = (RSAPublicKey) pemReader.readObject();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new ASN1OutputStream(baos)
            .writeObject(new org.bouncycastle.asn1.pkcs.RSAPublicKey(dirIdentityKey.getModulus(),
                    dirIdentityKey.getPublicExponent()).toASN1Primitive());
    byte[] pkcs = baos.toByteArray();
    byte[] dirIdentityKeyHashBytes = new byte[20];
    SHA1Digest sha1 = new SHA1Digest();
    sha1.update(pkcs, 0, pkcs.length);/*from w w w  .ja v  a  2  s  .  c  om*/
    sha1.doFinal(dirIdentityKeyHashBytes, 0);
    String keyHash = Hex.encodeHexString(dirIdentityKeyHashBytes);
    return keyHash;
}

From source file:alluxio.proxy.s3.S3RestServiceHandler.java

/**
 * @summary uploads an object or part of an object in multipart upload
 * @param contentMD5 the optional Base64 encoded 128-bit MD5 digest of the object
 * @param bucket the bucket name// w  w  w .java 2 s .  com
 * @param object the object name
 * @param partNumber the identification of the part of the object in multipart upload,
 *                   otherwise null
 * @param uploadId the upload ID of the multipart upload, otherwise null
 * @param is the request body
 * @return the response object
 */
@PUT
@Path(OBJECT_PARAM)
@ReturnType("java.lang.Void")
@Consumes(MediaType.WILDCARD)
public Response createObjectOrUploadPart(@HeaderParam("Content-MD5") final String contentMD5,
        @PathParam("bucket") final String bucket, @PathParam("object") final String object,
        @QueryParam("partNumber") final Integer partNumber, @QueryParam("uploadId") final Long uploadId,
        final InputStream is) {
    return S3RestUtils.call(bucket, new S3RestUtils.RestCallable<Response>() {
        @Override
        public Response call() throws S3Exception {
            Preconditions.checkNotNull(bucket, "required 'bucket' parameter is missing");
            Preconditions.checkNotNull(object, "required 'object' parameter is missing");
            Preconditions.checkArgument(
                    (partNumber == null && uploadId == null) || (partNumber != null && uploadId != null),
                    "'partNumber' and 'uploadId' parameter should appear together or be "
                            + "missing together.");

            String bucketPath = parseBucketPath(AlluxioURI.SEPARATOR + bucket);
            checkBucketIsAlluxioDirectory(bucketPath);

            String objectPath = bucketPath + AlluxioURI.SEPARATOR + object;
            if (partNumber != null) {
                // This object is part of a multipart upload, should be uploaded into the temporary
                // directory first.
                String tmpDir = S3RestUtils.getMultipartTemporaryDirForObject(bucketPath, object);
                checkUploadId(new AlluxioURI(tmpDir), uploadId);
                objectPath = tmpDir + AlluxioURI.SEPARATOR + Integer.toString(partNumber);
            }
            AlluxioURI objectURI = new AlluxioURI(objectPath);

            try {
                CreateFileOptions options = CreateFileOptions.defaults().setRecursive(true)
                        .setWriteType(getS3WriteType());
                FileOutStream os = mFileSystem.createFile(objectURI, options);
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                DigestOutputStream digestOutputStream = new DigestOutputStream(os, md5);

                try {
                    ByteStreams.copy(is, digestOutputStream);
                } finally {
                    digestOutputStream.close();
                }

                byte[] digest = md5.digest();
                String base64Digest = BaseEncoding.base64().encode(digest);
                if (contentMD5 != null && !contentMD5.equals(base64Digest)) {
                    // The object may be corrupted, delete the written object and return an error.
                    try {
                        mFileSystem.delete(objectURI);
                    } catch (Exception e2) {
                        // intend to continue and return BAD_DIGEST S3Exception.
                    }
                    throw new S3Exception(objectURI.getPath(), S3ErrorCode.BAD_DIGEST);
                }

                String entityTag = Hex.encodeHexString(digest);
                return Response.ok().tag(entityTag).build();
            } catch (Exception e) {
                throw toObjectS3Exception(e, objectPath);
            }
        }
    });
}

From source file:net.solarnetwork.node.io.rxtx.SerialPortSupport.java

private boolean handleSerialEventWithoutTimeout(SerialPortEvent event, InputStream in,
        ByteArrayOutputStream sink, byte[] magicBytes, int readLength) {
    int sinkSize = sink.size();
    boolean append = sinkSize > 0;
    byte[] buf = new byte[Math.min(readLength, 1024)];
    if (eventLog.isTraceEnabled()) {
        eventLog.trace("Sink contains {} bytes: {}", sinkSize, asciiDebugValue(sink.toByteArray()));
    }/*from w  ww. j av  a2  s.c  o  m*/
    try {
        int len = -1;
        final int max = Math.min(in.available(), buf.length);
        eventLog.trace("Attempting to read {} bytes from serial port", max);
        while (max > 0 && (len = in.read(buf, 0, max)) > 0) {
            sink.write(buf, 0, len);
            sinkSize += len;

            if (append) {
                // if we've collected at least desiredSize bytes, we're done
                if (sinkSize >= readLength) {
                    if (eventLog.isDebugEnabled()) {
                        eventLog.debug("Got desired {}  bytes of data: {}", readLength,
                                asciiDebugValue(sink.toByteArray()));
                    }
                    return true;
                }
                eventLog.debug("Looking for {} more bytes of data", (readLength - sinkSize));
                return false;
            } else {
                eventLog.trace("Looking for {} magic bytes 0x{}", magicBytes.length,
                        Hex.encodeHexString(magicBytes));
            }

            // look for magic in the buffer
            int magicIdx = 0;
            byte[] sinkBuf = sink.toByteArray();
            boolean found = false;
            for (; magicIdx < (sinkBuf.length - magicBytes.length + 1); magicIdx++) {
                found = true;
                for (int j = 0; j < magicBytes.length; j++) {
                    if (sinkBuf[magicIdx + j] != magicBytes[j]) {
                        found = false;
                        break;
                    }
                }
                if (found) {
                    break;
                }
            }

            if (found) {
                // magic found!
                if (eventLog.isTraceEnabled()) {
                    eventLog.trace("Found magic bytes " + asciiDebugValue(magicBytes) + " at buffer index "
                            + magicIdx);
                }

                // skip over magic bytes
                magicIdx += magicBytes.length;

                int count = readLength;
                count = Math.min(readLength, sinkBuf.length - magicIdx);
                sink.reset();
                sink.write(sinkBuf, magicIdx, count);
                sinkSize = count;
                if (eventLog.isTraceEnabled()) {
                    eventLog.trace("Sink contains {} bytes: {}", sinkSize, asciiDebugValue(sink.toByteArray()));
                }
                if (sinkSize >= readLength) {
                    // we got all the data here... we're done
                    return true;
                }
                eventLog.trace("Need {} more bytes of data", (readLength - sinkSize));
                append = true;
            } else if (sinkBuf.length > magicBytes.length) {
                // haven't found the magic yet, and the sink is larger than magic size, so 
                // trim sink down to just magic size
                sink.reset();
                sink.write(sinkBuf, sinkBuf.length - magicBytes.length - 1, magicBytes.length);
                sinkSize = magicBytes.length;
            }
        }
    } catch (IOException e) {
        log.error("Error reading from serial port: {}", e.getMessage());
        throw new RuntimeException(e);
    }

    if (eventLog.isTraceEnabled()) {
        eventLog.trace("Need {} more bytes of data, buffer: {}", (readLength - sinkSize),
                asciiDebugValue(sink.toByteArray()));
    }
    return false;
}

From source file:com.continusec.client.VerifiableMap.java

/**
 * Delete the value for a given key from the map. Calling this has the effect of adding a mutation to the
 * mutation log for the map, which then reflects in the root hash for the map. This occurs asynchronously.
 * @param key the key to delete.//  ww w  .ja v  a  2  s .  c  om
 * @return add entry response, which includes the Merkle Tree Leaf hash of the mutation log entry added.
 * @throws ContinusecException upon error
 */
public AddEntryResponse delete(byte[] key) throws ContinusecException {
    try {
        JsonObject j = new JsonParser()
                .parse(new String(this.client.makeRequest("DELETE",
                        this.path + "/key/h/" + Hex.encodeHexString(key), null, null).data, "UTF-8"))
                .getAsJsonObject();
        return new AddEntryResponse(Base64.decodeBase64(j.get("leaf_hash").getAsString()));
    } catch (UnsupportedEncodingException e1) {
        throw new ContinusecException(e1);
    }
}

From source file:at.gv.egiz.pdfas.lib.pki.impl.OCSPClient.java

/**
 * Retrieves an OCSP response for a certain certificate ({@code eeCertificate}) of a certain CA
 * ({@code issuerCertificate}).//ww w.  j av  a  2 s. c om
 * 
 * @param issuerCertificate The issuer certificate (required; must not be {@code null}).
 * @param eeCertificate     The end entity certificate (required; must not be {@code null}).
 * @return The OCSP response (never {@code null}) with guaranteed response status "successful" and with <strong>any
 *         revocation state</strong>.
 * @throws IOException              Thrown in case of error communicating with OCSP responder.
 * @throws OCSPClientException      In case the client could not process the response (e.g. non-successful response
 *                                  state like malformedRequest, internalError... or an unknown/unsupported response
 *                                  type).
 * @throws IllegalArgumentException In case the provided {@code eeCertificate} does not provide an OCSP responder
 *                                  url (use {@link Util#hasOcspResponder(X509Certificate)} in order to determine if
 *                                  it is safe to call this method) or the provided certificates could not be used
 *                                  for OCSP request creation.
 * @implNote This implementation just returns OCSP responses (<strong>of any revocation status</strong>) as they
 *           were retrieved from the OCSP responder (provided the response status indicates a successful response)
 *           without performing further checks like OCSP signature verification or OCSP responder certificate
 *           validation.
 */
public OCSPResponse getOcspResponse(X509Certificate issuerCertificate, X509Certificate eeCertificate)
        throws IOException, OCSPClientException {

    Objects.requireNonNull(issuerCertificate, "Issuer certificate required... must not be null.");
    Objects.requireNonNull(eeCertificate, "End-entity certificate required... must not be null.");

    StopWatch sw = new StopWatch();
    sw.start();

    if (log.isDebugEnabled()) {
        log.debug("Retrieving OCSP revocation info for: {}", eeCertificate.getSubjectDN());
    } else if (log.isInfoEnabled()) {
        log.info("Retrieving OCSP revocation info for certificate (SHA-1 fingerprint): {}",
                Hex.encodeHexString(eeCertificate.getFingerprintSHA()));
    }

    String ocspUrl = Util.getOcspUrl(eeCertificate);
    if (ocspUrl == null) {
        throw new IllegalArgumentException("The provided certificate does not feature an ocsp responder url.");
    }

    // create request
    byte[] ocspRequestEncoded;
    ReqCert reqCert;
    try {

        CertID certID = new CertID(AlgorithmID.sha1, issuerCertificate, eeCertificate);
        reqCert = new ReqCert(ReqCert.certID, certID);
        Request request = new Request(reqCert);
        OCSPRequest ocspRequest = new OCSPRequest();
        ocspRequest.setRequestList(new Request[] { request });
        ocspRequestEncoded = ocspRequest.getEncoded();

        if (log.isTraceEnabled()) {
            log.trace("Creating OCSP request: {}", request);
        }

    } catch (NoSuchAlgorithmException e) {
        // should not occur actually
        throw new IllegalStateException("Required algorithm (SHA-1) not available.", e);
    } catch (CodingException e) {
        throw new IllegalArgumentException(
                "Unable to encode ocsp request with the provided issuer and end-entity certificates.", e);
    }

    // https://tools.ietf.org/html/rfc6960
    // GET {url}/{url-encoding of base-64 encoding of the DER encoding of the OCSPRequest}
    String b64OcspRequest = org.apache.commons.codec.binary.Base64.encodeBase64String(ocspRequestEncoded);
    String urlEncodedB64OcspRequest = URLEncoder.encode(b64OcspRequest, "UTF-8");

    HttpRequestBase request;

    if (httpCachingEnabled && urlEncodedB64OcspRequest.length() <= 255) {
        // spec proposes GET request
        URI ocspResponderUri;
        try {
            URIBuilder uriBuilder = new URIBuilder(ocspUrl);
            uriBuilder
                    .setPath(StringUtils.appendIfMissing(uriBuilder.getPath(), "/") + urlEncodedB64OcspRequest);
            ocspResponderUri = uriBuilder.build();
        } catch (URISyntaxException e) {
            // can only occur with eeCertificate containing invalid ocsp responder url
            throw new IllegalArgumentException(
                    "Unable process OCSP responder uri of provided certificate: " + ocspUrl, e);
        }

        request = new HttpGet(ocspResponderUri);
        log.debug("Sending OCSP request using HTTP GET to: {}", ocspUrl);

    } else {
        // spec proposes POST request
        HttpPost httpPost = new HttpPost(ocspUrl);
        httpPost.setEntity(
                new ByteArrayEntity(ocspRequestEncoded, ContentType.create("application/ocsp-request")));
        request = httpPost;
        log.debug("Sending OCSP request using HTTP POST to: {}", ocspUrl);
    }

    request.setConfig(requestConfig);

    try (CloseableHttpResponse httpResponse = httpClient.execute(request)) {

        StatusLine statusLine = httpResponse.getStatusLine();
        log.debug("OCSP response HTTP status: {}", statusLine);
        if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
            throw new IOException("OCSP responder did not report HTTP 200: " + statusLine);
        }

        HttpEntity responseEntity = httpResponse.getEntity();

        OCSPResponse ocspResponse;
        try (InputStream in = responseEntity.getContent()) {

            ocspResponse = new OCSPResponse(in);

        } catch (UnknownResponseException e) {
            throw new OCSPClientException("Unknown (unsupported) OCSP response type: " + e.getResponseType(),
                    e);
        }

        if (log.isTraceEnabled()) {
            log.trace("OCSP response: {}", ocspResponse);
        }

        log.debug("OCSP response status: {}", ocspResponse.getResponseStatusName());
        if (ocspResponse.getResponseStatus() != OCSPResponse.successful) {
            throw new OCSPClientException("OCSP response status was not successful, got response status: "
                    + ocspResponse.getResponseStatusName());
        }

        // get the basic ocsp response (which is the only type currently supported, otherwise an
        // UnknownResponseException would have been thrown during parsing the response)
        BasicOCSPResponse basicOCSPResponse = (BasicOCSPResponse) ocspResponse.getResponse();

        // for future improvement: verify ocsp response, responder certificate...

        SingleResponse singleResponse;
        try {
            log.trace("Looking for OCSP response specific for: {}", reqCert);
            singleResponse = basicOCSPResponse.getSingleResponse(reqCert);
        } catch (OCSPException e) {
            try {
                singleResponse = basicOCSPResponse.getSingleResponse(issuerCertificate, eeCertificate, null);
            } catch (OCSPException e1) {
                throw new OCSPClientException(
                        "Unable to process received OCSP response for the provided certificate (SHA-1 fingerprint): "
                                + Hex.encodeHexString(eeCertificate.getFingerprintSHA()),
                        e1);
            }
        }

        if (log.isTraceEnabled()) {
            log.trace("OCSP respose for specific certificate: {}", singleResponse);
        }

        CertStatus certStatus = singleResponse.getCertStatus();
        String formattedThisUpdate = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT
                .format(singleResponse.getThisUpdate());
        log.info("Certificate revocation state (@{}}: {}", formattedThisUpdate, certStatus);

        sw.stop();
        log.debug("OCSP query took: {}ms", sw.getTime());

        return ocspResponse;

    } // close httpResponse

}

From source file:com.tremolosecurity.saml.Saml2Assertion.java

private Assertion generateAssertion(String id2) {
    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);//from  ww w . j  a v  a  2  s  . co  m

    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();

    AssertionBuilder assertionBuilder = new AssertionBuilder();

    Assertion assertion = assertionBuilder.buildObject();

    assertion.setID(id);

    IssuerBuilder issuerBuilder = new IssuerBuilder();

    Issuer issuer = issuerBuilder.buildObject();

    issuer.setValue(this.issuer);

    assertion.setIssuer(issuer);

    // Get the subject builder based on the subject element name
    SubjectBuilder builder = new SubjectBuilder();

    // Create the subject
    Subject subject = builder.buildObject();

    SubjectConfirmationBuilder scb = new SubjectConfirmationBuilder();
    SubjectConfirmation sc = scb.buildObject();
    sc.setMethod(SubjectConfirmation.METHOD_BEARER);

    SubjectConfirmationDataBuilder scdb = new SubjectConfirmationDataBuilder();
    SubjectConfirmationData scd = scdb.buildObject();
    scd.setNotOnOrAfter(this.notAfter);
    scd.setRecipient(this.recepient);

    sc.setSubjectConfirmationData(scd);
    subject.getSubjectConfirmations().add(sc);
    NameIDBuilder nameIDBuilder = new NameIDBuilder();

    NameID nameID = nameIDBuilder.buildObject();
    nameID.setValue(this.subject);
    nameID.setFormat(this.nameIDFormat);

    // Added an NameID and two SubjectConfirmation items - creation of these items is not shown
    subject.setNameID(nameID);
    assertion.setSubject(subject);

    AuthnStatementBuilder authnStmtBuilder = new AuthnStatementBuilder();
    AuthnStatement authn = authnStmtBuilder.buildObject();
    authn.setAuthnInstant(this.issueInstant);
    AuthnContextBuilder authnCtxBuilder = new AuthnContextBuilder();
    AuthnContext authnCtx = authnCtxBuilder.buildObject();
    AuthnContextClassRefBuilder accrb = new AuthnContextClassRefBuilder();
    AuthnContextClassRef accrf = accrb.buildObject();
    accrf.setAuthnContextClassRef(this.authnContextRef);
    authnCtx.setAuthnContextClassRef(accrf);
    authn.setAuthnContext(authnCtx);
    //AuthnContextClassRefBuilder accrb = new AuthnContextClassRefBuilder();
    //AuthnContextClassRef accr = accrb.buildObject();
    //accr.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified");
    authn.setSessionIndex(id);
    //authnCtx.setAuthnContextClassRef(accr);
    //authn.setAuthnContext(authnCtx);

    assertion.getAuthnStatements().add(authn);

    AttributeStatementBuilder attrb = new AttributeStatementBuilder();
    AttributeStatement attrStmt = attrb.buildObject();

    boolean addAttrs = false;

    Iterator<Attribute> attrs = this.attribs.iterator();
    while (attrs.hasNext()) {
        Attribute attrib = attrs.next();
        AttributeBuilder attrBuilder = new AttributeBuilder();
        org.opensaml.saml.saml2.core.Attribute samlAttrib = attrBuilder.buildObject();
        samlAttrib.setName(attrib.getName());
        Iterator<String> attrVals = attrib.getValues().iterator();
        while (attrVals.hasNext()) {
            XSStringBuilder sb = new XSStringBuilder();
            XSString val = sb.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME);
            val.setValue(attrVals.next());
            samlAttrib.getAttributeValues().add(val);
            addAttrs = true;
        }

        attrStmt.getAttributes().add(samlAttrib);
    }

    if (addAttrs) {
        assertion.getAttributeStatements().add(attrStmt);
    }

    ConditionsBuilder cb = new ConditionsBuilder();
    Conditions conditions = cb.buildObject();
    conditions.setNotBefore(this.notBefore);
    conditions.setNotOnOrAfter(this.notAfter);

    AudienceRestrictionBuilder arb = new AudienceRestrictionBuilder();
    AudienceRestriction ar = arb.buildObject();
    AudienceBuilder ab = new AudienceBuilder();
    Audience a = ab.buildObject();

    a.setAudienceURI(this.audience);

    ar.getAudiences().add(a);

    conditions.getAudienceRestrictions().add(ar);

    assertion.setConditions(conditions);

    assertion.setIssueInstant(this.issueInstant);

    return assertion;
}

From source file:be.fedict.eid.applet.service.signer.time.TSPTimeStampService.java

public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
    // digest the message
    MessageDigest messageDigest = MessageDigest.getInstance(this.digestAlgo);
    byte[] digest = messageDigest.digest(data);

    // generate the TSP request
    BigInteger nonce = new BigInteger(128, new SecureRandom());
    TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
    requestGenerator.setCertReq(true);/*from w w  w  . ja v a  2  s .c om*/
    if (null != this.requestPolicy) {
        requestGenerator.setReqPolicy(this.requestPolicy);
    }
    TimeStampRequest request = requestGenerator.generate(this.digestAlgoOid, digest, nonce);
    byte[] encodedRequest = request.getEncoded();

    // create the HTTP client
    HttpClient httpClient = new HttpClient();
    if (null != this.username) {
        Credentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    if (null != this.proxyHost) {
        httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort);
    }

    // create the HTTP POST request
    PostMethod postMethod = new PostMethod(this.tspServiceUrl);
    RequestEntity requestEntity = new ByteArrayRequestEntity(encodedRequest, "application/timestamp-query");
    postMethod.addRequestHeader("User-Agent", this.userAgent);
    postMethod.setRequestEntity(requestEntity);

    // invoke TSP service
    int statusCode = httpClient.executeMethod(postMethod);
    if (HttpStatus.SC_OK != statusCode) {
        LOG.error("Error contacting TSP server " + this.tspServiceUrl);
        throw new Exception("Error contacting TSP server " + this.tspServiceUrl);
    }

    // HTTP input validation
    Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type");
    if (null == responseContentTypeHeader) {
        throw new RuntimeException("missing Content-Type header");
    }
    String contentType = responseContentTypeHeader.getValue();
    if (!contentType.startsWith("application/timestamp-reply")) {
        LOG.debug("response content: " + postMethod.getResponseBodyAsString());
        throw new RuntimeException("invalid Content-Type: " + contentType);
    }
    if (0 == postMethod.getResponseContentLength()) {
        throw new RuntimeException("Content-Length is zero");
    }

    // TSP response parsing and validation
    InputStream inputStream = postMethod.getResponseBodyAsStream();
    TimeStampResponse timeStampResponse = new TimeStampResponse(inputStream);
    timeStampResponse.validate(request);

    if (0 != timeStampResponse.getStatus()) {
        LOG.debug("status: " + timeStampResponse.getStatus());
        LOG.debug("status string: " + timeStampResponse.getStatusString());
        PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
        if (null != failInfo) {
            LOG.debug("fail info int value: " + failInfo.intValue());
            if (PKIFailureInfo.unacceptedPolicy == failInfo.intValue()) {
                LOG.debug("unaccepted policy");
            }
        }
        throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
    }
    TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded());
    LOG.debug("signer cert serial number: " + signerCertSerialNumber);
    LOG.debug("signer cert issuer: " + signerCertIssuer);

    // TSP signer certificates retrieval
    CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection",
            BouncyCastleProvider.PROVIDER_NAME);
    Collection<? extends Certificate> certificates = certStore.getCertificates(null);
    X509Certificate signerCert = null;
    Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>();
    for (Certificate certificate : certificates) {
        X509Certificate x509Certificate = (X509Certificate) certificate;
        if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal())
                && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
            signerCert = x509Certificate;
        }
        String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate));
        certificateMap.put(ski, x509Certificate);
        LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski);
    }

    // TSP signer cert path building
    if (null == signerCert) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>();

    X509Certificate tsaIssuer = loadCertificate(
            "be/fedict/eid/applet/service/CA POLITICA SELLADO DE TIEMPO - COSTA RICA.crt");
    X509Certificate rootCA = loadCertificate("be/fedict/eid/applet/service/CA RAIZ NACIONAL COSTA RICA.cer");
    LOG.debug("adding to certificate chain: " + signerCert.getSubjectX500Principal());
    tspCertificateChain.add(signerCert);
    LOG.debug("adding to certificate chain: " + tsaIssuer.getSubjectX500Principal());
    tspCertificateChain.add(tsaIssuer);
    LOG.debug("adding to certificate chain: " + rootCA.getSubjectX500Principal());
    tspCertificateChain.add(rootCA);

    // verify TSP signer signature
    timeStampToken.validate(tspCertificateChain.get(0), BouncyCastleProvider.PROVIDER_NAME);

    // verify TSP signer certificate
    this.validator.validate(tspCertificateChain, revocationData);

    LOG.debug("time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());

    byte[] timestamp = timeStampToken.getEncoded();
    return timestamp;
}

From source file:com.puppetlabs.puppetdb.javaclient.impl.PuppetDBClientImpl.java

protected UUID postCommand(String command, int version, Object payload) throws IOException {
    CommandObject cmdObj = new CommandObject();
    cmdObj.setCommand(command);/*  w w w.j  a  v a 2s.  c om*/
    cmdObj.setVersion(version);
    cmdObj.setPayload(payload);

    String json = connector.toJSON(cmdObj);
    Map<String, String> params = new HashMap<String, String>();
    params.put("payload", json);
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        params.put("checksum", Hex.encodeHexString(md.digest(json.getBytes(HttpConnector.UTF_8))));
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException(e);
    }

    CommandResponse response = connector.post("/commands/", params, CommandResponse.class);
    return response == null ? null : UUID.fromString(response.getUuid());
}

From source file:eu.europa.ec.markt.dss.validation.pades.PDFDocumentValidator.java

@Override
protected SignatureLevelLTV verifyLevelLTV(AdvancedSignature signature, Date referenceTime,
        ValidationContext ctx) {/*from  ww  w .j  a  v  a2s .c  om*/
    try {
        PAdESSignature pades = (PAdESSignature) signature;
        LOG.info("Starting LTV validation of signature: " + pades.getPdfPkcs7().getSignName() + " / "
                + PdfPKCS7.getSubjectFields(pades.getPdfPkcs7().getSigningCertificate()));

        PdfDictionary catalog = pades.getOuterCatalog();
        if (catalog == null) {
            catalog = pades.getPdfReader().getCatalog();
        }

        PdfDictionary dss = catalog.getAsDict(new PdfName("DSS"));

        if (dss == null) {
            LOG.info("No DSS dictionary!");
            return new SignatureLevelLTV(new Result(ResultStatus.INVALID, "no.dss.dictionary"), null, null);
        }

        LOG.info("DSS dictionary found");

        PdfName sigType = pades.getSignatureDictionary().getAsName(PdfName.TYPE);
        // PdfName subfilter = pades.getSignatureDictionary().getAsName(PdfName.SUBFILTER);

        TimestampVerificationResult docTimestampCheck = null;

        boolean dssCertsVerificationResult = everyCertificateValueAreThere(ctx,
                pades.getExtendedCertificateSource().getCertificates(), pades.getSigningCertificate());
        boolean dssRevocationVerificationResult = true;
        dssRevocationVerificationResult &= everyCRLValueOrRefAreThere(ctx, pades.getCRLs());
        dssRevocationVerificationResult &= everyOCSPValueOrRefAreThere(ctx, pades.getOCSPs());
        boolean vriVerificationresult = true;

        if (sigType != null) {
            if (sigType.equals(new PdfName("Sig"))) {
                // Standard signature

                PdfDictionary vri = dss.getAsDict(new PdfName("VRI"));

                if (vri == null) {
                    LOG.info("No VRI dictionary, this is optional but required by Adobe Acrobat");
                    return new SignatureLevelLTV(new Result(ResultStatus.INVALID, "no.vri.dictionary"), null,
                            null);
                }

                // Verify the VRI
                MessageDigest _md = MessageDigest.getInstance("SHA1");
                String hexHash = Hex
                        .encodeHexString(
                                _md.digest(pades.getSignatureDictionary().get(PdfName.CONTENTS).getBytes()))
                        .toUpperCase();

            } else if (sigType.equals(new PdfName("DocTimeStamp"))) {

            } else {
                throw new RuntimeException("Unknown signature dictionary type");
            }
        }

        Result levelReached = null;
        if (dssCertsVerificationResult && dssRevocationVerificationResult) {
            levelReached = new Result(ResultStatus.VALID, null);
        } else {
            levelReached = new Result();
            if (!dssCertsVerificationResult) {
                levelReached.setStatus(ResultStatus.INVALID, "dss.certs.verification.result.error");
            } else if (!dssRevocationVerificationResult) {
                levelReached.setStatus(ResultStatus.INVALID, "dss.revocation.verification.result.error");
            } else if (!vriVerificationresult) {
                levelReached.setStatus(ResultStatus.INVALID, "vri.verification.result.error");
            }
        }

        return new SignatureLevelLTV(levelReached,
                new Result((dssCertsVerificationResult) ? ResultStatus.VALID : ResultStatus.INVALID, null),
                new Result((dssRevocationVerificationResult) ? ResultStatus.VALID : ResultStatus.INVALID,
                        null));

    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:libepg.epg.section.sectionreconstructor.SectionReconstructor.java

/**
 * ??????????????????/*ww w.j  a  v a 2s.  com*/
 * ByteBuffer?array()????????????????????
 *
 */
private synchronized void addToReturnObject(ByteBuffer buf, Set<byte[]> dest) {
    byte[] BeforeCutDown = buf.array();
    byte[] AfterCutDown = new byte[buf.position()];
    System.arraycopy(BeforeCutDown, 0, AfterCutDown, 0, AfterCutDown.length);
    if (LOG.isTraceEnabled()) {
        MessageFormat msg1 = new MessageFormat("\n??={0}\n?={1}");
        Object[] parameters1 = { Hex.encodeHexString(BeforeCutDown), Hex.encodeHexString(AfterCutDown) };
        LOG.trace(msg1.format(parameters1));
    }
    if (dest.add(AfterCutDown)) {
        if (LOG.isTraceEnabled()) {
            MessageFormat msg2 = new MessageFormat("\n???={0}");
            Object[] parameters2 = { Hex.encodeHexString(AfterCutDown) };
            LOG.trace(msg2.format(parameters2));
        }
    } else if (LOG.isTraceEnabled()) {
        MessageFormat msg3 = new MessageFormat("\n???????={0}");
        Object[] parameters3 = { Hex.encodeHexString(AfterCutDown) };
        LOG.trace(msg3.format(parameters3));
    }
}