Example usage for java.security.cert CertificateFactory generateCertificate

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

Introduction

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

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:org.ejbca.extra.db.CardRenewalResponse.java

private X509Certificate getCert(String tag) {
    CertificateFactory cf = CertTools.getCertificateFactory();
    X509Certificate cert = null;/* w  w w .  j a  v  a 2  s  . c  om*/
    try {
        String certStr = (String) data.get(tag);
        if (StringUtils.isNotEmpty(certStr)) {
            cert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(Base64.decode((certStr).getBytes())));
        }
    } catch (CertificateException e) {
        log.error("Error decoding certificate ", e);
    }
    return cert;
}

From source file:org.strongswan.android.ui.activity.TrustedCertificateImportActivity.java

/**
 * Load the file from the given URI and try to parse it as X.509 certificate.
 *
 * @param uri/*from ww w  . ja v  a 2s  .co m*/
 * @return certificate or null
 */
private X509Certificate parseCertificate(Uri uri) {
    X509Certificate certificate = null;
    try {
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        InputStream in = getContentResolver().openInputStream(uri);
        certificate = (X509Certificate) factory.generateCertificate(in);
        /* we don't check whether it's actually a CA certificate or not */
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return certificate;
}

From source file:com.netflix.ice.login.saml.Saml.java

public Saml(Properties properties) throws LoginMethodException {
    super(properties);
    config = new SamlConfig(properties);
    for (String signingCert : config.trustedSigningCerts) {
        try {// ww  w  .j  a v a 2  s.  com
            FileInputStream fis = new FileInputStream(new File(signingCert));
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            Certificate cert = certFactory.generateCertificate(fis);
            trustedSigningCerts.add(cert);
        } catch (IOException ioe) {
            logger.error("Error reading public key " + signingCert + ":" + ioe.toString());
        } catch (Exception e) {
            logger.error("Error decoding public key " + signingCert + ":" + e.toString());
        }
    }

    try {
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException ce) {
        throw new LoginMethodException("Failure to init OpenSAML: " + ce.toString());
    }
}

From source file:org.linagora.linshare.core.facade.webservice.user.impl.DocumentFacadeImpl.java

@Override
public DocumentDto createWithSignature(File tempFile, String fileName, String description,
        InputStream signatureFile, String signatureFileName, InputStream x509) throws BusinessException {
    Validate.notNull(tempFile, "Missing required file (check parameter named file)");
    User actor = checkAuthentication();//from  ww  w . ja  v  a  2s  .co m
    if ((actor.isGuest() && !actor.getCanUpload()))
        throw new BusinessException(BusinessErrorCode.WEBSERVICE_FORBIDDEN,
                "You are not authorized to use this service");
    DocumentEntry res = documentEntryService.create(actor, actor, tempFile, fileName, description, false, null);
    if (signatureFile != null) {
        X509Certificate x509certificate = null;
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            x509certificate = (X509Certificate) cf.generateCertificate(x509);
        } catch (CertificateException e) {
            throw new BusinessException(BusinessErrorCode.INVALID_INPUT_FOR_X509_CERTIFICATE,
                    "unable to generate a X509 certificate", e);
        }
        signatureService.createSignature(actor, res.getDocument(), signatureFile, signatureFileName,
                x509certificate);
    }

    documentEntryService.updateFileProperties(actor, actor, res.getUuid(), res.getName(), description, null);
    return new DocumentDto(res);
}

From source file:test.unit.be.fedict.eid.idp.protocol.ws_federation.WSFederationMetadataHttpServletTest.java

private X509Certificate generateSelfSignedCertificate(KeyPair keyPair, String subjectDn, DateTime notBefore,
        DateTime notAfter) throws Exception {
    PublicKey subjectPublicKey = keyPair.getPublic();
    PrivateKey issuerPrivateKey = keyPair.getPrivate();
    String signatureAlgorithm = "SHA1WithRSAEncryption";
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.reset();//  w  ww  .  j a v a2  s. c o  m
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setSignatureAlgorithm(signatureAlgorithm);
    certificateGenerator.setNotBefore(notBefore.toDate());
    certificateGenerator.setNotAfter(notAfter.toDate());
    X509Principal issuerDN = new X509Principal(subjectDn);
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(new X509Principal(subjectDn));
    certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom()));

    certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            createSubjectKeyId(subjectPublicKey));
    PublicKey issuerPublicKey;
    issuerPublicKey = subjectPublicKey;
    certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            createAuthorityKeyId(issuerPublicKey));

    certificateGenerator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true));

    X509Certificate certificate;
    certificate = certificateGenerator.generate(issuerPrivateKey);

    /*
     * Next certificate factory trick is needed to make sure that the
     * certificate delivered to the caller is provided by the default
     * security provider instead of BouncyCastle. If we don't do this trick
     * we might run into trouble when trying to use the CertPath validator.
     */
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(certificate.getEncoded()));
    return certificate;
}

From source file:com.linkedin.pinot.common.utils.ClientSSLContextGenerator.java

private TrustManager[] setupTrustManagers()
        throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
    // This is the cert authority that validates server's cert, so we need to put it in our
    // trustStore.
    if (_serverCACertFile != null) {
        LOGGER.info("Initializing trust store from {}", _serverCACertFile);
        FileInputStream is = new FileInputStream(new File(_serverCACertFile));
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null);// w  w w  .  j av a2s  . co m
        CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        int i = 0;
        while (is.available() > 0) {
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is);
            LOGGER.info("Read certificate serial number {} by issuer {} ", cert.getSerialNumber().toString(16),
                    cert.getIssuerDN().toString());

            String serverKey = "https-server-" + i;
            trustStore.setCertificateEntry(serverKey, cert);
            i++;
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(CERTIFICATE_TYPE);
        tmf.init(trustStore);
        LOGGER.info("Successfully initialized trust store");
        return tmf.getTrustManagers();
    }
    // Server verification disabled. Trust all servers
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } };
    return trustAllCerts;
}

From source file:com.connectsdk.service.config.WebOSTVServiceConfig.java

private X509Certificate loadCertificateFromPEM(String pemString) {
    CertificateFactory certFactory;
    try {//from   www  .  j av a2 s .c  o  m
        certFactory = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream inputStream = new ByteArrayInputStream(pemString.getBytes("US-ASCII"));

        return (X509Certificate) certFactory.generateCertificate(inputStream);
    } catch (CertificateException e) {
        e.printStackTrace();
        return null;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.apache.tomcat.util.net.puretls.PureTLSSupport.java

public Object[] getPeerCertificateChain(boolean force) throws IOException {
    Vector v = ssl.getCertificateChain();

    if (v == null && force) {
        SSLPolicyInt policy = new SSLPolicyInt();
        policy.requireClientAuth(true);//  w  w  w.j a  va  2  s. c  om
        policy.handshakeOnConnect(false);
        policy.waitOnClose(false);
        ssl.renegotiate(policy);
        v = ssl.getCertificateChain();
    }

    if (v == null)
        return null;

    java.security.cert.X509Certificate[] chain = new java.security.cert.X509Certificate[v.size()];

    try {
        for (int i = 1; i <= v.size(); i++) {
            // PureTLS provides cert chains with the peer
            // cert last but the Servlet 2.3 spec (S 4.7) requires
            // the opposite order so we reverse the chain as we go
            byte buffer[] = ((X509Cert) v.elementAt(v.size() - i)).getDER();

            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            ByteArrayInputStream stream = new ByteArrayInputStream(buffer);

            X509Certificate xCert = (X509Certificate) cf.generateCertificate(stream);
            chain[i - 1] = xCert;
            if (logger.isTraceEnabled()) {
                logger.trace("Cert # " + i + " = " + xCert);
            }
        }
    } catch (java.security.cert.CertificateException e) {
        logger.info("JDK's broken cert handling can't parse this certificate (which PureTLS likes)", e);
        throw new IOException("JDK's broken cert handling can't parse this certificate (which PureTLS likes)");
    }
    return chain;
}

From source file:com.cloud.bridge.auth.ec2.AuthenticationHandler.java

/**
 * For EC2 SOAP calls this function's goal is to extract the X509 certificate that is
 * part of the WS-Security wrapped SOAP request.   We need the cert in order to 
 * map it to the user's Cloud API key and Cloud Secret Key.
 *///from w ww . j  a  v  a 2s.  c  o m
public InvocationResponse invoke(MessageContext msgContext) throws AxisFault {
    // -> the certificate we want is embedded into the soap header
    try {
        SOAPEnvelope soapEnvelope = msgContext.getEnvelope();
        String xmlHeader = soapEnvelope.toString();
        //System.out.println( "entire request: " + xmlHeader );

        InputStream is = new ByteArrayInputStream(xmlHeader.getBytes("UTF-8"));
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document request = db.parse(is);
        NodeList certs = request.getElementsByTagNameNS(
                "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                "BinarySecurityToken");
        if (0 < certs.getLength()) {
            Node item = certs.item(0);
            String result = new String(item.getFirstChild().getNodeValue());
            byte[] certBytes = Base64.decodeBase64(result.getBytes());

            Certificate userCert = null;
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            ByteArrayInputStream bs = new ByteArrayInputStream(certBytes);
            while (bs.available() > 0)
                userCert = cf.generateCertificate(bs);
            //System.out.println( "cert: " + userCert.toString());              
            String uniqueId = AuthenticationUtils.X509CertUniqueId(userCert);
            logger.debug("X509 cert's uniqueId: " + uniqueId);

            // -> find the Cloud API key and the secret key from the cert's uniqueId 
            /*               UserCredentialsDao credentialDao = new UserCredentialsDao();
                           UserCredentials cloudKeys = credentialDao.getByCertUniqueId( uniqueId );
            */
            UserCredentialsVO cloudKeys = ucDao.getByCertUniqueId(uniqueId);
            if (null == cloudKeys) {
                logger.error("Cert does not map to Cloud API keys: " + uniqueId);
                throw new AxisFault("User not properly registered: Certificate does not map to Cloud API Keys",
                        "Client.Blocked");
            } else
                UserContext.current().initContext(cloudKeys.getAccessKey(), cloudKeys.getSecretKey(),
                        cloudKeys.getAccessKey(), "SOAP Request", null);
            //System.out.println( "end of cert match: " + UserContext.current().getSecretKey());
        }
    } catch (AxisFault e) {
        throw e;
    } catch (Exception e) {
        logger.error("EC2 Authentication Handler: ", e);
        throw new AxisFault("An unknown error occurred.", "Server.InternalError");
    }
    return InvocationResponse.CONTINUE;
}

From source file:test.unit.be.fedict.eid.idp.protocol.ws_federation.sts.SecurityTokenServicePortImplTest.java

@Test
public void testValidation() throws Exception {
    // setup/*from  www .  j  a v a  2s. co m*/
    InputStream requestInputStream = SecurityTokenServicePortImplTest.class
            .getResourceAsStream("/sts-validation-request.xml");
    assertNotNull(requestInputStream);

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(requestInputStream);

    Element requestSecurityTokenElement = (Element) document
            .getElementsByTagNameNS("http://docs.oasis-open.org/ws-sx/ws-trust/200512", "RequestSecurityToken")
            .item(0);

    Element x509Certificate = (Element) document
            .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "X509Certificate").item(0);
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(x509Certificate.getFirstChild().getNodeValue())));
    List<X509Certificate> certificateChain = Collections.singletonList(certificate);

    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class,
            be.fedict.eid.idp.wstrust.jaxb.wspolicy.ObjectFactory.class,
            be.fedict.eid.idp.wstrust.jaxb.wsaddr.ObjectFactory.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    JAXBElement<RequestSecurityTokenType> resultElement = (JAXBElement<RequestSecurityTokenType>) unmarshaller
            .unmarshal(requestSecurityTokenElement);
    RequestSecurityTokenType requestSecurityToken = resultElement.getValue();

    SecurityTokenServicePortImpl testedInstance = new SecurityTokenServicePortImpl();

    WebServiceContext mockWebServiceContext = EasyMock.createMock(WebServiceContext.class);
    injectResource(mockWebServiceContext, testedInstance);

    MessageContext mockMessageContext = EasyMock.createMock(MessageContext.class);

    EasyMock.expect(mockWebServiceContext.getMessageContext()).andStubReturn(mockMessageContext);

    ServletContext mockServletContext = EasyMock.createMock(ServletContext.class);

    EasyMock.expect(mockMessageContext.get(MessageContext.SERVLET_CONTEXT)).andReturn(mockServletContext);

    IdentityProviderConfiguration mockIdentityProviderConfiguration = EasyMock
            .createMock(IdentityProviderConfiguration.class);

    EasyMock.expect(mockServletContext.getAttribute(
            IdentityProviderConfigurationFactory.IDENTITY_PROVIDER_CONFIGURATION_CONTEXT_ATTRIBUTE))
            .andReturn(mockIdentityProviderConfiguration);

    EasyMock.expect(mockIdentityProviderConfiguration.getIdentityCertificateChain())
            .andReturn(certificateChain);

    EasyMock.expect(mockIdentityProviderConfiguration.getDefaultIssuer()).andReturn("e-contract-2012");

    Element samlElement = (Element) document
            .getElementsByTagNameNS(WSTrustConstants.SAML2_NAMESPACE, "Assertion").item(0);
    EasyMock.expect(mockMessageContext.get(WSSecuritySoapHandler.class.getName() + ".samlToken"))
            .andStubReturn(samlElement);

    // prepare
    EasyMock.replay(mockWebServiceContext, mockMessageContext, mockServletContext,
            mockIdentityProviderConfiguration);

    // operate
    RequestSecurityTokenResponseCollectionType result = testedInstance
            .requestSecurityToken(requestSecurityToken);

    // verify
    EasyMock.verify(mockWebServiceContext, mockMessageContext, mockServletContext,
            mockIdentityProviderConfiguration);
    assertNotNull(result);

    List<RequestSecurityTokenResponseType> resultList = result.getRequestSecurityTokenResponse();
    assertEquals(1, resultList.size());
    RequestSecurityTokenResponseType requestSecurityTokenResponse = resultList.get(0);
    List<Object> responseObjects = requestSecurityTokenResponse.getAny();
    boolean valid = false;
    String reason = null;
    for (Object responseObject : responseObjects) {
        LOG.debug("response object type: " + responseObject);
        if (responseObject instanceof JAXBElement) {
            JAXBElement jaxbElement = (JAXBElement) responseObject;
            QName qname = jaxbElement.getName();
            LOG.debug("qname: " + qname);
            if (new QName(WSTrustConstants.WS_TRUST_NAMESPACE, "Status").equals(qname)) {
                StatusType status = (StatusType) jaxbElement.getValue();
                String code = status.getCode();
                LOG.debug("status code: " + code);
                if (WSTrustConstants.VALID_STATUS_CODE.equals(code)) {
                    valid = true;
                }
                reason = status.getReason();
            }
        }
    }
    LOG.debug("status reason: " + reason);
    assertTrue(reason.indexOf("policy") != -1);
}