Example usage for java.security.cert CertificateFactory getInstance

List of usage examples for java.security.cert CertificateFactory getInstance

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory getInstance.

Prototype

public static final CertificateFactory getInstance(String type) throws CertificateException 

Source Link

Document

Returns a certificate factory object that implements the specified certificate type.

Usage

From source file:com.securekey.samplerp.web.BriidgeController.java

@RequestMapping(value = "verifyJWT.json", method = { RequestMethod.GET, RequestMethod.POST })
public @ResponseBody String verifyJWT(@RequestParam("jwt") String jwt) throws Exception {

    JWSObject jws = JWSObject.parse(jwt);
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(jws.getHeader().getX509CertURL().toString());
    request.addHeader("Accept", "text/plain");

    try {//from  ww w.  j a v a 2s  .co  m
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();

        if (entity != null) {

            String pemFileContent = entity == null ? null : EntityUtils.toString(entity);
            PemReader pemReader = new PemReader(new StringReader(pemFileContent));
            byte[] pubK = pemReader.readPemObject().getContent();
            pemReader.close();
            Certificate serverCert = CertificateFactory.getInstance("X.509")
                    .generateCertificate(new ByteArrayInputStream(pubK));
            pemReader.close();

            if (serverCert instanceof X509Certificate) {

                X509Certificate cert = (X509Certificate) serverCert;
                PublicKey publicKey = cert.getPublicKey();
                if (publicKey instanceof RSAPublicKey) {
                    JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) publicKey);
                    if (jws.verify(verifier)) {
                        return "{\"status\":\"jwt_verified\"}";
                    } else {
                        return "{\"status\":\"jwt_verify_fail\"}";
                    }
                } else {
                    return "{\"status\":\"jwt_pub_key_not_rsa\"}";
                }

            } else {
                return "{\"status\":\"jwt_pem_not_cert\"}";
            }
        } else {
            return "{\"status\":\"jwt_pem_download_fail\"}";
        }
    } catch (IOException e) {
        return "{\"status\":\"jwt_pem_download_fail\"}";
    }
}

From source file:org.kaazing.maven.plugins.TrustStoreMojo.java

KeyStore getTrustStore(Map<String, String> certs, String storeType) throws Exception {

    KeyStore ks = KeyStore.getInstance(storeType);

    // Initialize an empty keystore
    ks.load(null, null);//from   w w  w  .  j a va  2  s . co m

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

    for (Map.Entry<String, String> elt : certs.entrySet()) {
        String alias = elt.getKey();

        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(elt.getValue().getBytes(UTF8));

            X509Certificate cert = (X509Certificate) certFactory.generateCertificate(bais);
            cert.checkValidity();

            getLog().info(String.format("Adding certificate with alias '%s'", alias));
            ks.setCertificateEntry(alias, cert);

        } catch (CertificateExpiredException cee) {
            getLog().error(String.format("NOT Adding certificate %s: %s", alias, cee));

        } catch (CertificateNotYetValidException cnyve) {
            getLog().error(String.format("NOT Adding certificate %s: %s", alias, cnyve));
        }
    }

    return ks;
}

From source file:org.taverna.server.master.worker.SecurityContextDelegate.java

@Override
public void validateTrusted(Trust t) throws InvalidCredentialException {
    InputStream contentsAsStream;
    if (t.certificateBytes != null && t.certificateBytes.length > 0) {
        contentsAsStream = new ByteArrayInputStream(t.certificateBytes);
        t.certificateFile = null;//from  w ww  .ja  va2s . c  o m
    } else if (t.certificateFile == null || t.certificateFile.trim().isEmpty())
        throw new InvalidCredentialException("absent or empty certificateFile");
    else {
        contentsAsStream = contents(t.certificateFile);
        t.certificateBytes = null;
    }
    t.serverName = null;
    if (t.fileType == null || t.fileType.trim().isEmpty())
        t.fileType = CERTIFICATE_TYPE;
    t.fileType = t.fileType.trim();
    try {
        t.loadedCertificates = CertificateFactory.getInstance(t.fileType)
                .generateCertificates(contentsAsStream);
        t.serverName = new ArrayList<>(t.loadedCertificates.size());
        for (Certificate c : t.loadedCertificates)
            t.serverName.add(getPrincipalName(((X509Certificate) c).getSubjectX500Principal()));
    } catch (CertificateException e) {
        throw new InvalidCredentialException(e);
    } catch (ClassCastException e) {
        // Do nothing; truncates the list of server names
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.pades.PAdESSignature.java

@Override
public ListCRLSource getCRLSource() {

    PdfDict dss = getDSSDictionary();/*  w  ww  .  j  av  a 2  s . co  m*/
    try {

        List<X509CRL> list = new ArrayList<X509CRL>();
        if (dss != null) {

            PdfArray crlArray = dss.getAsArray("CRLs");
            if (crlArray != null) {

                CertificateFactory factory = CertificateFactory.getInstance("X509");
                for (int i = 0; i < crlArray.size(); i++) {

                    byte[] stream = crlArray.getBytes(i);
                    X509CRL cert = (X509CRL) factory.generateCRL(new ByteArrayInputStream(stream));
                    if (!list.contains(cert)) {

                        list.add(cert);
                    }
                }
            }
        }
        if (list.size() > 0) {
            return new ListCRLSource(list);
        }
    } catch (IOException ex) {

        throw new DSSException(ex);
    } catch (CertificateException e) {

        throw new DSSException(e);
    } catch (CRLException e) {

        throw new DSSException(e);
    }
    return null;
}

From source file:com.google.appengine.tck.appidentity.AppIdentityServiceTest.java

@Test
public void testGetPublicCertificates() throws Exception {
    Collection<PublicCertificate> certs = appIdentity.getPublicCertificatesForApp();
    Assert.assertTrue("No certificates returned.", !certs.isEmpty());

    for (PublicCertificate publicCert : certs) {
        Assert.assertTrue("No name for certificate.", !publicCert.getCertificateName().trim().isEmpty());

        String pemFormat = publicCert.getX509CertificateInPemFormat();
        String errMsg = "getX509CertificateInPemFormat():" + pemFormat;
        // TODO better check?
        Assert.assertTrue(errMsg, pemFormat.startsWith("-----BEGIN"));
        Assert.assertTrue(errMsg, pemFormat.contains("-----END"));

        InputStream stream = new ByteArrayInputStream(
                publicCert.getX509CertificateInPemFormat().getBytes("UTF-8"));
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate cert = cf.generateCertificate(stream);

        PublicKey pk = cert.getPublicKey();
        Assert.assertNotNull(pk.getEncoded());
    }/*from   w ww .  j a v  a 2s.c  om*/
}

From source file:be.fedict.eid.dss.client.DigitalSignatureServiceClient.java

/**
 * Main constructor.// w ww.  ja v a2s. co m
 * 
 * @param endpointAddress
 *            the DSS web service endpoint address. For example
 *            http://localhost:8080/eid-dss-ws/dss
 */
public DigitalSignatureServiceClient(String endpointAddress) {
    this.endpointAddress = endpointAddress;
    this.dssObjectFactory = new ObjectFactory();
    this.vrObjectFactory = new be.fedict.eid.dss.ws.profile.vr.jaxb.ObjectFactory();
    try {
        JAXBContext vrJAXBContext = JAXBContext
                .newInstance(be.fedict.eid.dss.ws.profile.vr.jaxb.ObjectFactory.class);
        this.vrMarshaller = vrJAXBContext.createMarshaller();
        this.vrUnmarshaller = vrJAXBContext.createUnmarshaller();

        JAXBContext artifactJAXBContext = JAXBContext
                .newInstance(be.fedict.eid.dss.ws.profile.artifact.jaxb.ObjectFactory.class);
        this.artifactMarshaller = artifactJAXBContext.createMarshaller();
        this.artifactUnmarshaller = artifactJAXBContext.createUnmarshaller();

        JAXBContext originalDocumentJAXBContext = JAXBContext
                .newInstance(be.fedict.eid.dss.ws.profile.originaldocument.jaxb.ObjectFactory.class);
        this.originalDocumentMarshaller = originalDocumentJAXBContext.createMarshaller();
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    try {
        this.documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("document builder error: " + e.getMessage(), e);
    }

    try {
        this.certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("X509 factory error: " + e.getMessage(), e);
    }

    this.port = getPort();
}

From source file:com.evilisn.DAO.CertMapper.java

public static X509Certificate getX509Certificate(byte[] bcert) throws CertificateException, IOException {
    if (bcert == null)
        return null;
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(bcert);
    X509Certificate x509cert = (X509Certificate) cf.generateCertificate(bais);

    cf = null;/*from www.j  a  v  a 2  s.  c o  m*/
    bais.close();
    return x509cert;
}

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

/**
 * Main constructor.//from w  w  w.  j a v a2s. c o  m
 * 
 * @param address
 *            the location of the DSSP web service.
 */
public DigitalSignatureServiceClient(String address) {
    DigitalSignatureService digitalSignatureService = DigitalSignatureServiceFactory.newInstance();
    this.dssPort = digitalSignatureService.getDigitalSignatureServicePort();

    BindingProvider bindingProvider = (BindingProvider) this.dssPort;
    bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, address);

    Binding binding = bindingProvider.getBinding();
    List<Handler> handlerChain = binding.getHandlerChain();
    this.attachmentsSOAPHandler = new AttachmentsLogicalHandler();
    handlerChain.add(this.attachmentsSOAPHandler);
    this.wsSecuritySOAPHandler = new WSSecuritySOAPHandler();
    handlerChain.add(this.wsSecuritySOAPHandler);
    this.wsTrustSOAPHandler = new WSTrustSOAPHandler();
    handlerChain.add(this.wsTrustSOAPHandler);
    // cannot add LoggingSOAPHandler here, else we break SOAP with
    // attachments on Apache CXF
    binding.setHandlerChain(handlerChain);

    this.objectFactory = new ObjectFactory();
    this.wstObjectFactory = new be.e_contract.dssp.ws.jaxb.wst.ObjectFactory();
    this.dsObjectFactory = new be.e_contract.dssp.ws.jaxb.xmldsig.ObjectFactory();
    this.asyncObjectFactory = new be.e_contract.dssp.ws.jaxb.dss.async.ObjectFactory();
    this.wsseObjectFactory = new be.e_contract.dssp.ws.jaxb.wsse.ObjectFactory();
    this.vrObjectFactory = new be.e_contract.dssp.ws.jaxb.dss.vr.ObjectFactory();

    this.secureRandom = new SecureRandom();
    this.secureRandom.setSeed(System.currentTimeMillis());

    try {
        this.certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java

public X509Certificate generateV1Certificate(String subject, char[] ksPass, KeyStore keyStore)
        throws OperatorCreationException, IOException, CertificateException, KeyStoreException,
        NoSuchAlgorithmException {
    KeyPair pair = generateKeyPair();

    BigInteger certSerial = BigInteger.valueOf(System.currentTimeMillis());
    X500Name issuerDN = new X500Name("CN=" + subject);
    X500Name subjectDN = new X500Name("CN=" + subject);
    Date notBefore = new Date(System.currentTimeMillis() - 10000);
    Date notAfter = new Date(System.currentTimeMillis() + 10000);
    PublicKey pubKey = (pair.getPublic());
    X509v1CertificateBuilder certGen = new JcaX509v1CertificateBuilder(issuerDN, certSerial, notBefore,
            notAfter, subjectDN, pubKey);

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").build(pair.getPrivate());
    byte[] encoded = certGen.build(signer).getEncoded();
    CertificateFactory fact = CertificateFactory.getInstance("X.509");
    InputStream is = new ByteArrayInputStream(encoded);
    X509Certificate generateCertificate = (X509Certificate) fact.generateCertificate(is);
    is.close();/* w  ww  .  j  ava2  s .c o m*/

    // set the CA cert as trusted root
    X509Certificate[] chain = new X509Certificate[] { generateCertificate };
    addToKeyStore(pair, chain, K_NAME, keyStore, ksPass);

    String certStr = generateCertificate.toString();

    return generateCertificate;
}

From source file:be.e_contract.eid.applet.service.impl.handler.IdentityDataMessageHandler.java

/**
 * Tries to parse the X509 certificate./*from   w  w  w  .j ava  2 s.  c o  m*/
 * 
 * @param certFile
 * @return the X509 certificate, or <code>null</code> in case of a DER
 *         decoding error.
 */
private X509Certificate getCertificate(byte[] certFile) {
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(certFile));
        return certificate;
    } catch (CertificateException e) {
        LOG.warn("certificate error: " + e.getMessage(), e);
        LOG.debug("certificate size: " + certFile.length);
        LOG.debug("certificate file content: " + Hex.encodeHexString(certFile));
        /*
         * Missing eID authentication and eID non-repudiation certificates
         * could become possible for future eID cards. A missing certificate
         * is represented as a block of 1300 null bytes.
         */
        if (1300 == certFile.length) {
            boolean missingCertificate = true;
            for (int idx = 0; idx < certFile.length; idx++) {
                if (0 != certFile[idx]) {
                    missingCertificate = false;
                }
            }
            if (missingCertificate) {
                LOG.debug("the certificate data indicates a missing certificate");
            }
        }
        return null;
    }
}