Example usage for java.security.cert CertificateException getMessage

List of usage examples for java.security.cert CertificateException getMessage

Introduction

In this page you can find the example usage for java.security.cert CertificateException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:be.fedict.eid.tsl.TrustService.java

public X509Certificate getServiceDigitalIdentity() {
    TSPServiceInformationType tspServiceInformation = this.tspService.getServiceInformation();
    DigitalIdentityListType digitalIdentityList = tspServiceInformation.getServiceDigitalIdentity();
    try {//from   w w w .ja v a  2 s.  co m
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        for (final DigitalIdentityType digitalIdentity : digitalIdentityList.getDigitalId()) {
            byte[] x509CertificateData = digitalIdentity.getX509Certificate();
            if (x509CertificateData != null) {
                try {
                    X509Certificate certificate = (X509Certificate) certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateData));
                    return certificate;
                } catch (CertificateException e) {
                    throw new RuntimeException("X509 error: " + e.getMessage(), e);
                }
            }
        }
        throw new RuntimeException("No X509Certificate identity specified");
    } catch (CertificateException e) {
        throw new RuntimeException("X509 error: " + e.getMessage(), e);
    }
}

From source file:be.fedict.eid.tsl.TrustService.java

public byte[] getServiceDigitalIdentityData() {
    TSPServiceInformationType tspServiceInformation = this.tspService.getServiceInformation();
    DigitalIdentityListType digitalIdentityList = tspServiceInformation.getServiceDigitalIdentity();
    try {//  w  w  w  . j  av a 2s.  c  om
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        for (final DigitalIdentityType digitalIdentity : digitalIdentityList.getDigitalId()) {
            byte[] x509CertificateData = digitalIdentity.getX509Certificate();
            if (x509CertificateData != null) {
                try {
                    X509Certificate certificate = (X509Certificate) certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateData));
                    return x509CertificateData;
                } catch (CertificateException e) {
                    throw new RuntimeException("X509 error: " + e.getMessage(), e);
                }
            }
        }
        throw new RuntimeException("No X509Certificate identity specified");
    } catch (CertificateException e) {
        throw new RuntimeException("X509 error: " + e.getMessage(), e);
    }
}

From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java

private X509Certificate getCertificate(byte[] certData) {
    CertificateFactory certificateFactory;
    try {/*  w  w w.  j av a  2 s . c  o  m*/
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("cert factory error: " + e.getMessage(), e);
    }
    try {
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(certData));
        return certificate;
    } catch (CertificateException e) {
        throw new RuntimeException("certificate decoding error: " + e.getMessage(), e);
    }
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

/**
 * Get the trusted keystore as configured in the extension properties.
 * //from   ww w  . j  a  v  a 2 s. c o m
 * @return
 */
private KeyStore getTrustedKeyStore() {
    try {
        String keystorePassword = config
                .getProperty(RepositoryManagedSignatureProviderFactory.TRUSTED_KEYSTORE_PASSWORD);
        String keystorePath = config
                .getProperty(RepositoryManagedSignatureProviderFactory.TRUSTED_KEYSTORE_PATH);
        KeyStore keystore = KeyStore.getInstance("pkcs12");
        FileInputStream keyStream = new FileInputStream(keystorePath);
        keystore.load(keyStream, keystorePassword.toCharArray());

        // return the keystore
        return keystore;
    } catch (KeyStoreException kse) {
        throw new AlfrescoRuntimeException(kse.getMessage());
    } catch (java.security.cert.CertificateException ce) {
        throw new AlfrescoRuntimeException(ce.getMessage());
    } catch (NoSuchAlgorithmException nsaex) {
        throw new AlfrescoRuntimeException(nsaex.getMessage());
    } catch (IOException ioex) {
        throw new AlfrescoRuntimeException(ioex.getMessage());
    }
}

From source file:nl.nikhef.eduroam.WiFiEduroam.java

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
// Step 3 for android 4.0 - 4.2
private void installClientCertificate() {
    try {/* w  w  w. j a  v  a2 s .c  o  m*/
        updateStatus("Inputting client certificate.");

        // Parse the certificate that we got from the server
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(
                Base64.decode(certificate.replaceAll("-----(BEGIN|END) CERTIFICATE-----", "")));
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);

        client_cert_name = ssid + " " + INT_CLIENT_CERT_NAME;

        // Create a pkcs12 certificate/private key combination
        Security.addProvider(new BouncyCastleProvider());
        KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(null, null);
        Certificate chain[] = new Certificate[] { (Certificate) cert };
        keystore.setKeyEntry(client_cert_name, csr.getPrivate(), null, chain);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        keystore.store(out, ssid.toCharArray());
        out.flush();
        byte[] buffer = out.toByteArray();
        out.close();

        // Install the private key/client certificate combination
        Intent intent = KeyChain.createInstallIntent();
        intent.putExtra(KeyChain.EXTRA_NAME, ssid + " " + INT_CLIENT_CERT_NAME);
        intent.putExtra(KeyChain.EXTRA_PKCS12, buffer);
        startActivityForResult(intent, 3);
    } catch (CertificateException e) {
        e.printStackTrace();
        throw new RuntimeException("Certificate error.");
    } catch (KeyStoreException e) {
        e.printStackTrace();
        System.out.println(e.getMessage());
        throw new RuntimeException("Certificate error: KeyStore");
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        throw new RuntimeException("Certificate error: Provider");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new RuntimeException("Certificate error: Algorithm");
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("Certificate error: IO");
    }
}

From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java

public void importCertToStore(String fileName, String certData, String keyStoreName)
        throws SecurityConfigException {
    try {/*w ww .j av  a  2 s. c  o m*/
        if (keyStoreName == null) {
            throw new SecurityConfigException("Key Store name can't be null");
        }

        KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
        KeyStore ks = keyMan.getKeyStore(keyStoreName);

        byte[] bytes = Base64.decode(certData);
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate cert;
        try {
            cert = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(bytes));
        } catch (CertificateException e) {
            log.error(e.getMessage(), e);
            throw new SecurityConfigException("Invalid format of the provided certificate file");
        }

        if (ks.getCertificateAlias(cert) != null) {
            // We already have this certificate in the key store - ignore
            // adding it twice
            return;
        }

        ks.setCertificateEntry(fileName, cert);

        keyMan.updateKeyStore(keyStoreName, ks);

    } catch (SecurityConfigException e) {
        throw e;
    } catch (Exception e) {
        String msg = "Error when importing cert to the keyStore";
        log.error(msg, e);
        throw new SecurityConfigException(msg, e);
    }

}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

@Override
public KeyStore getUserKeyStore(String storePassword) {

    try {/*w  ww.ja v  a  2s. c  o m*/
        NodeRef person = serviceRegistry.getPersonService().getPerson(user);

        if (person == null) {
            return null;
        }

        KeyStore keystore = KeyStore.getInstance("pkcs12");

        // check to see if a keystore exists for this user
        NodeRef keystoreNode = counterSignService.getSignatureArtifact(person,
                CounterSignSignatureModel.ASSOC_SIGNERKEYSTORE);

        // if no keystore, create one, persist it and associate it with the user
        if (keystoreNode == null) {
            keystore = createUserKeyStore(person, storePassword);
        } else {
            // open the reader to the key and load it
            ContentReader keyReader = serviceRegistry.getContentService().getReader(keystoreNode,
                    ContentModel.PROP_CONTENT);
            keystore.load(keyReader.getContentInputStream(), storePassword.toCharArray());
        }

        // return the keystore
        return keystore;
    } catch (KeyStoreException kse) {
        throw new AlfrescoRuntimeException(kse.getMessage());
    } catch (java.security.cert.CertificateException ce) {
        throw new AlfrescoRuntimeException(ce.getMessage());
    } catch (NoSuchAlgorithmException nsaex) {
        throw new AlfrescoRuntimeException(nsaex.getMessage());
    } catch (IOException ioex) {
        throw new AlfrescoRuntimeException(ioex.getMessage());
    } catch (NoSuchProviderException nspex) {
        throw new AlfrescoRuntimeException(nspex.getMessage());
    }
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int)
 *//*from  w ww. j ava  2 s .co  m*/
public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword,
        final int validityPeriod, final int keySize) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", subjectData);
        DEBUGGER.debug("Value: {}", validityPeriod);
        DEBUGGER.debug("Value: {}", keySize);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final String signatureAlgorithm = certConfig.getSignatureAlgorithm();
    final String certificateAlgorithm = certConfig.getCertificateAlgorithm();
    final File privateKeyDirectory = FileUtils
            .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0));
    final File publicKeyDirectory = FileUtils
            .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0));
    final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0));
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0));
    final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O="
            + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C="
            + subjectData.get(5) + ",E=" + subjectData.get(6));

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm);
        DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm);
        DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory);
        DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory);
        DEBUGGER.debug("csrDirectory: {}", csrDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("x500Name: {}", x500Name);
    }

    File csrFile = null;
    JcaPEMWriter csrPemWriter = null;
    JcaPEMWriter publicKeyWriter = null;
    JcaPEMWriter privateKeyWriter = null;
    FileOutputStream csrFileStream = null;
    FileOutputStream keyStoreStream = null;
    FileOutputStream publicKeyFileStream = null;
    FileOutputStream privateKeyFileStream = null;
    OutputStreamWriter csrFileStreamWriter = null;
    OutputStreamWriter privateKeyStreamWriter = null;
    OutputStreamWriter publicKeyStreamWriter = null;

    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm);
        keyGenerator.initialize(keySize, random);

        if (DEBUG) {
            DEBUGGER.debug("KeyGenerator: {}", keyGenerator);
        }

        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (DEBUG) {
            DEBUGGER.debug("KeyPair: {}", keyPair);
        }

        if (keyPair != null) {
            final Signature sig = Signature.getInstance(signatureAlgorithm);
            final PrivateKey privateKey = keyPair.getPrivate();
            final PublicKey publicKey = keyPair.getPublic();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
                DEBUGGER.debug("PrivateKey: {}", privateKey);
                DEBUGGER.debug("PublicKey: {}", publicKey);
            }

            sig.initSign(privateKey, random);
            ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey);

            if (DEBUG) {
                DEBUGGER.debug("ContentSigner: {}", signGen);
            }

            Calendar expiry = Calendar.getInstance();
            expiry.add(Calendar.DAY_OF_YEAR, validityPeriod);

            if (DEBUG) {
                DEBUGGER.debug("Calendar: {}", expiry);
            }

            CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

            if (DEBUG) {
                DEBUGGER.debug("CertificateFactory: {}", certFactory);
            }

            X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory
                    .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) };

            if (DEBUG) {
                DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert);
            }

            keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate(
                    new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()))));
            keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(),
                    certFactory.generateCertificate(new FileInputStream(
                            FileUtils.getFile(certConfig.getIntermediateCertificateFile()))));

            PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name,
                    publicKey);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder);
            }

            PKCS10CertificationRequest csr = builder.build(signGen);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequest: {}", csr);
            }

            // write private key
            File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFile: {}", privateKeyFile);
            }

            if (!(privateKeyFile.createNewFile())) {
                throw new IOException("Failed to store private file");
            }

            privateKeyFileStream = new FileOutputStream(privateKeyFile);
            privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream);
                DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter);
            }

            privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter);
            privateKeyWriter.writeObject(privateKey);
            privateKeyWriter.flush();
            privateKeyStreamWriter.flush();
            privateKeyFileStream.flush();

            // write public key
            File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFile: {}", publicKeyFile);
            }

            if (!(publicKeyFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            publicKeyFileStream = new FileOutputStream(publicKeyFile);
            publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter);
            publicKeyWriter.writeObject(publicKey);
            publicKeyWriter.flush();
            publicKeyStreamWriter.flush();
            publicKeyFileStream.flush();

            // write csr
            csrFile = FileUtils
                    .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("csrFile: {}", csrFile);
            }

            if (!(csrFile.createNewFile())) {
                throw new IOException("Failed to store CSR file");
            }

            csrFileStream = new FileOutputStream(csrFile);
            csrFileStreamWriter = new OutputStreamWriter(csrFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            csrPemWriter = new JcaPEMWriter(csrFileStreamWriter);
            csrPemWriter.writeObject(csr);
            csrPemWriter.flush();
            csrFileStreamWriter.flush();
            csrFileStream.flush();

            File keyStoreFile = FileUtils
                    .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType());

            if (DEBUG) {
                DEBUGGER.debug("keyStoreFile: {}", keyStoreFile);
            }

            keyStoreStream = FileUtils.openOutputStream(keyStoreFile);

            if (DEBUG) {
                DEBUGGER.debug("keyStoreStream: {}", keyStoreStream);
            }

            keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(),
                    issuerCert);
            keyStore.store(keyStoreStream, storePassword.toCharArray());
            keyStoreStream.flush();

            if (DEBUG) {
                DEBUGGER.debug("KeyStore: {}", keyStore);
            }
        } else {
            throw new CertificateManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (InvalidKeyException ikx) {
        throw new CertificateManagementException(ikx.getMessage(), ikx);
    } catch (OperatorCreationException ocx) {
        throw new CertificateManagementException(ocx.getMessage(), ocx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } finally {
        if (csrFileStreamWriter != null) {
            IOUtils.closeQuietly(csrFileStreamWriter);
        }

        if (csrFileStream != null) {
            IOUtils.closeQuietly(csrFileStream);
        }

        if (csrPemWriter != null) {
            IOUtils.closeQuietly(csrPemWriter);
        }

        if (publicKeyFileStream != null) {
            IOUtils.closeQuietly(publicKeyFileStream);
        }

        if (publicKeyStreamWriter != null) {
            IOUtils.closeQuietly(publicKeyStreamWriter);
        }

        if (publicKeyWriter != null) {
            IOUtils.closeQuietly(publicKeyWriter);
        }

        if (privateKeyFileStream != null) {
            IOUtils.closeQuietly(privateKeyFileStream);
        }

        if (privateKeyStreamWriter != null) {
            IOUtils.closeQuietly(privateKeyStreamWriter);
        }

        if (privateKeyWriter != null) {
            IOUtils.closeQuietly(privateKeyWriter);
        }

        if (keyStoreStream != null) {
            IOUtils.closeQuietly(keyStoreStream);
        }
    }

    return csrFile;
}

From source file:be.e_contract.dssp.client.DigitalSignatureServiceClient.java

/**
 * Verifies the signatures on the given document.
 * /*  ww w .j av a2  s  .c om*/
 * @param mimetype
 *            the mime-type of the document.
 * @param data
 *            the document data.
 * @param useAttachments
 *            <code>true</code> when you want to use SOAP attachments.
 * @return the verification result.
 * @throws UnsupportedDocumentTypeException
 *             for unsupported mime-types
 * @throws DocumentSignatureException
 *             when the document or signature is incorrect.
 */
public VerificationResult verify(String mimetype, byte[] data, boolean useAttachments)
        throws UnsupportedDocumentTypeException, DocumentSignatureException {
    List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>();

    VerifyRequest verifyRequest = this.objectFactory.createVerifyRequest();
    verifyRequest.setProfile(DigitalSignatureServiceConstants.PROFILE);
    InputDocuments inputDocuments = this.objectFactory.createInputDocuments();
    verifyRequest.setInputDocuments(inputDocuments);
    addDocument(mimetype, data, useAttachments, inputDocuments);

    AnyType optionalInputs = this.objectFactory.createAnyType();
    verifyRequest.setOptionalInputs(optionalInputs);
    ReturnVerificationReport returnVerificationReport = this.vrObjectFactory.createReturnVerificationReport();
    optionalInputs.getAny().add(returnVerificationReport);
    returnVerificationReport.setIncludeVerifier(false);
    returnVerificationReport.setIncludeCertificateValues(true);

    this.wsSecuritySOAPHandler.setSession(null);
    ResponseBaseType response = this.dssPort.verify(verifyRequest);

    Result result = response.getResult();
    String resultMajor = result.getResultMajor();
    String resultMinor = result.getResultMinor();
    if (false == DigitalSignatureServiceConstants.SUCCESS_RESULT_MAJOR.equals(resultMajor)) {
        if (DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR.equals(resultMajor)) {
            if (DigitalSignatureServiceConstants.UNSUPPORTED_MIME_TYPE_RESULT_MINOR.equals(resultMinor)) {
                throw new UnsupportedDocumentTypeException();
            }
            if (DigitalSignatureServiceConstants.INCORRECT_SIGNATURE_RESULT_MINOR.equals(resultMinor)) {
                throw new DocumentSignatureException();
            }
        }
        throw new RuntimeException("not successfull: " + resultMajor + " " + resultMinor);
    }

    DateTime timeStampRenewalBefore = null;
    AnyType optionalOutputs = response.getOptionalOutputs();
    List<Object> optionalOutputsList = optionalOutputs.getAny();
    for (Object optionalOutput : optionalOutputsList) {
        if (false == optionalOutput instanceof JAXBElement) {
            continue;
        }
        JAXBElement jaxbElement = (JAXBElement) optionalOutput;
        LOG.debug("optional output: " + optionalOutput.getClass().getName());
        if (jaxbElement.getValue() instanceof DeadlineType) {
            DeadlineType deadlineType = (DeadlineType) jaxbElement.getValue();
            timeStampRenewalBefore = new DateTime(deadlineType.getBefore().toGregorianCalendar());
        } else if (jaxbElement.getValue() instanceof VerificationReportType) {
            LOG.debug("found VerificationReport");
            VerificationReportType verificationReport = (VerificationReportType) jaxbElement.getValue();
            List<IndividualReportType> individualReports = verificationReport.getIndividualReport();
            for (IndividualReportType individualReport : individualReports) {

                if (!DigitalSignatureServiceConstants.SUCCESS_RESULT_MAJOR
                        .equals(individualReport.getResult().getResultMajor())) {
                    LOG.warn("some invalid VR result reported: "
                            + individualReport.getResult().getResultMajor());
                    continue;
                }
                SignedObjectIdentifierType signedObjectIdentifier = individualReport
                        .getSignedObjectIdentifier();
                Date signingTime = signedObjectIdentifier.getSignedProperties().getSignedSignatureProperties()
                        .getSigningTime().toGregorianCalendar().getTime();
                String location = signedObjectIdentifier.getSignedProperties().getSignedSignatureProperties()
                        .getLocation();
                SignerRoleType signerRole = signedObjectIdentifier.getSignedProperties()
                        .getSignedSignatureProperties().getSignerRole();
                String role = null;
                if (null != signerRole) {
                    ClaimedRolesListType claimedRolesList = signerRole.getClaimedRoles();
                    if (null != claimedRolesList) {
                        List<be.e_contract.dssp.ws.jaxb.xades.AnyType> claimedRoles = claimedRolesList
                                .getClaimedRole();
                        be.e_contract.dssp.ws.jaxb.xades.AnyType claimedRole = claimedRoles.get(0);
                        role = claimedRole.getContent().get(0).toString();
                    }
                }

                List<Object> details = individualReport.getDetails().getAny();
                X509Certificate certificate = null;
                String name = null;
                for (Object detail : details) {
                    if (detail instanceof JAXBElement<?>) {
                        JAXBElement<?> detailElement = (JAXBElement<?>) detail;
                        if (detailElement.getValue() instanceof DetailedSignatureReportType) {
                            DetailedSignatureReportType detailedSignatureReport = (DetailedSignatureReportType) detailElement
                                    .getValue();

                            List<CertificateValidityType> certificateValidities = detailedSignatureReport
                                    .getCertificatePathValidity().getPathValidityDetail()
                                    .getCertificateValidity();
                            CertificateValidityType certificateValidity = certificateValidities.get(0);
                            name = certificateValidity.getSubject();
                            byte[] encodedCertificate = certificateValidity.getCertificateValue();
                            try {
                                certificate = (X509Certificate) this.certificateFactory
                                        .generateCertificate(new ByteArrayInputStream(encodedCertificate));
                            } catch (CertificateException e) {
                                throw new RuntimeException("cert decoding error: " + e.getMessage(), e);
                            }
                        }
                    }
                }
                signatureInfos.add(new SignatureInfo(name, certificate, signingTime, role, location));
            }
        }
    }

    if (signatureInfos.isEmpty()) {
        return null;
    }
    return new VerificationResult(signatureInfos, timeStampRenewalBefore);
}

From source file:org.signserver.web.GenericProcessServlet.java

private void processRequest(final HttpServletRequest req, final HttpServletResponse res, final int workerId,
        final byte[] data, String fileName, final String pdfPassword, final ProcessType processType,
        final MetaDataHolder metadataHolder) throws java.io.IOException, ServletException {
    final String remoteAddr = req.getRemoteAddr();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Recieved HTTP process request for worker " + workerId + ", from ip " + remoteAddr);
    }//  w w w  .ja  va 2 s .  c  o  m

    // Client certificate
    Certificate clientCertificate = null;
    Certificate[] certificates = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
    if (certificates != null) {
        clientCertificate = certificates[0];
    }

    // Create request context and meta data
    final RequestContext context = new RequestContext(clientCertificate, remoteAddr);
    RequestMetadata metadata = RequestMetadata.getInstance(context);

    IClientCredential credential;

    if (clientCertificate instanceof X509Certificate) {
        final X509Certificate cert = (X509Certificate) clientCertificate;
        LOG.debug("Authentication: certificate");
        credential = new CertificateClientCredential(cert.getSerialNumber().toString(16),
                cert.getIssuerDN().getName());
    } else {
        // Check is client supplied basic-credentials
        final String authorization = req.getHeader(HTTP_AUTH_BASIC_AUTHORIZATION);
        if (authorization != null) {
            LOG.debug("Authentication: password");

            final String decoded[] = new String(Base64.decode(authorization.split("\\s")[1])).split(":", 2);

            credential = new UsernamePasswordClientCredential(decoded[0], decoded[1]);
        } else {
            LOG.debug("Authentication: none");
            credential = null;
        }
    }
    context.put(RequestContext.CLIENT_CREDENTIAL, credential);

    // Create log map
    LogMap logMap = LogMap.getInstance(context);

    final String xForwardedFor = req.getHeader(RequestContext.X_FORWARDED_FOR);

    // Add HTTP specific log entries
    logMap.put(IWorkerLogger.LOG_REQUEST_FULLURL,
            req.getRequestURL().append("?").append(req.getQueryString()).toString());
    logMap.put(IWorkerLogger.LOG_REQUEST_LENGTH, String.valueOf(data.length));
    logMap.put(IWorkerLogger.LOG_FILENAME, fileName);
    logMap.put(IWorkerLogger.LOG_XFORWARDEDFOR, xForwardedFor);
    logMap.put(IWorkerLogger.LOG_WORKER_NAME,
            getWorkerSession().getCurrentWorkerConfig(workerId).getProperty(PropertiesConstants.NAME));

    if (xForwardedFor != null) {
        context.put(RequestContext.X_FORWARDED_FOR, xForwardedFor);
    }

    // Store filename for use by archiver etc
    if (fileName != null) {
        fileName = stripPath(fileName);
    }
    context.put(RequestContext.FILENAME, fileName);
    context.put(RequestContext.RESPONSE_FILENAME, fileName);

    // PDF Password
    if (pdfPassword != null) {
        metadata.put(RequestContext.METADATA_PDFPASSWORD, pdfPassword);
    }

    addRequestMetaData(metadataHolder, metadata);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Received bytes of length: " + data.length);
    }

    final int requestId = random.nextInt();

    try {
        String responseText;

        switch (processType) {
        case signDocument:
            final GenericServletResponse servletResponse = (GenericServletResponse) getWorkerSession().process(
                    new AdminInfo("Client user", null, null), workerId,
                    new GenericServletRequest(requestId, data, req), context);

            if (servletResponse.getRequestID() != requestId) { // TODO: Is this possible to get at all?
                LOG.error("Response ID " + servletResponse.getRequestID() + " not matching request ID "
                        + requestId);
                res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Request and response ID missmatch");
                return;
            }

            byte[] processedBytes = (byte[]) servletResponse.getProcessedData();

            res.setContentType(servletResponse.getContentType());
            Object responseFileName = context.get(RequestContext.RESPONSE_FILENAME);
            if (responseFileName instanceof String) {
                res.setHeader("Content-Disposition", "attachment; filename=\"" + responseFileName + "\"");
            }
            res.setContentLength(processedBytes.length);
            res.getOutputStream().write(processedBytes);
            break;
        case validateDocument:
            final GenericValidationResponse validationResponse = (GenericValidationResponse) getWorkerSession()
                    .process(new AdminInfo("Client user", null, null), workerId,
                            new GenericValidationRequest(requestId, data), context);

            responseText = validationResponse.isValid() ? "VALID" : "INVALID";

            if (LOG.isDebugEnabled()) {
                final Validation validation = validationResponse.getCertificateValidation();

                if (validation != null) {
                    LOG.debug("Cert validation status: "
                            + validationResponse.getCertificateValidation().getStatusMessage());
                }
            }

            res.setContentType("text/plain");
            res.setContentLength(responseText.getBytes().length);
            res.getOutputStream().write(responseText.getBytes());
            break;
        case validateCertificate:
            final Certificate cert;
            try {
                cert = CertTools.getCertfromByteArray(data);

                final String certPurposes = req.getParameter(CERT_PURPOSES_PROPERTY_NAME);
                final ValidateResponse certValidationResponse = (ValidateResponse) getWorkerSession().process(
                        new AdminInfo("Client user", null, null), workerId,
                        new ValidateRequest(cert, certPurposes), context);
                final Validation validation = certValidationResponse.getValidation();

                final StringBuilder sb = new StringBuilder(validation.getStatus().name());

                sb.append(";");

                final String validPurposes = certValidationResponse.getValidCertificatePurposes();

                if (validPurposes != null) {
                    sb.append(certValidationResponse.getValidCertificatePurposes());
                }
                sb.append(";");
                sb.append(certValidationResponse.getValidation().getStatusMessage());
                sb.append(";");
                sb.append(certValidationResponse.getValidation().getRevokationReason());
                sb.append(";");

                final Date revocationDate = certValidationResponse.getValidation().getRevokedDate();

                if (revocationDate != null) {
                    sb.append(certValidationResponse.getValidation().getRevokedDate().getTime());
                }

                responseText = sb.toString();

                res.setContentType("text/plain");
                res.setContentLength(responseText.getBytes().length);
                res.getOutputStream().write(responseText.getBytes());
            } catch (CertificateException e) {
                LOG.error("Invalid certificate: " + e.getMessage());
                sendBadRequest(res, "Invalid certificate: " + e.getMessage());
                return;
            }
            break;
        }
        ;

        res.getOutputStream().close();

    } catch (AuthorizationRequiredException e) {
        LOG.debug("Sending back HTTP 401: " + e.getLocalizedMessage());

        final String httpAuthBasicRealm = "SignServer Worker " + workerId;

        res.setHeader(HTTP_AUTH_BASIC_WWW_AUTHENTICATE, "Basic realm=\"" + httpAuthBasicRealm + "\"");
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
    } catch (AccessDeniedException e) {
        LOG.debug("Sending back HTTP 403: " + e.getLocalizedMessage());
        res.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
    } catch (NoSuchWorkerException ex) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Worker Not Found");
    } catch (IllegalRequestException e) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (CryptoTokenOfflineException e) {
        res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
    } catch (ServiceUnavailableException e) {
        res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
    } catch (NotGrantedException e) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
    } catch (SignServerException e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}