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.teknux.jettybootstrap.keystore.JettyKeystoreConvertorBuilder.java

public JettyKeystoreConvertorBuilder setCertificateFromPKCS8(InputStream inputStream, String certificateType)
        throws JettyKeystoreException {
    try {/* w  w w. j  a v a 2s.  c o  m*/
        CertificateFactory certificateFactory = CertificateFactory.getInstance(certificateType);
        certificate = certificateFactory.generateCertificate(inputStream);

        return this;
    } catch (CertificateException e) {
        throw new JettyKeystoreException(JettyKeystoreException.ERROR_LOAD_CERTIFICATE_PKCS8,
                "Can not load certificate (PKCS8)", e);
    }
}

From source file:be.apsu.extremon.probes.tsp.TSPProbe.java

public TSPProbe() throws Exception {
    this.delay = confInt("delay", DEFAULT_DELAY);
    this.running = false;
    getAllowedSignatureOIDs(confStr(ALLOWED_SIGNATURE_CERTIFICATE_ALGORITHMS).split(","));

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    url = new URL(confStr("url"));

    this.requestGenerator = new TimeStampRequestGenerator();
    this.requestGenerator.setCertReq(true);

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    String encodedCert = confStr("tsa.certificate");
    X509Certificate tsaCert = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(encodedCert)));
    JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder();
    this.signerVerifier = verifierBuilder.build(tsaCert);

    this.random = new Random();

    start();/*from   w w  w . j a  v  a 2 s.com*/
    log("initialized");
}

From source file:be.apsu.extremon.probes.xkms2.XKMS2Probe.java

public XKMS2Probe() throws CertificateException {
    super();//from w  ww.  ja  va  2 s. c o m
    this.trustService = new XKMS2Client(confStr("url"));
    this.certChain = new LinkedList<X509Certificate>();
    this.delay = confInt("delay", DEFAULT_DELAY);
    this.domain = confStr("trust.domain").toUpperCase();
    this.returnRevocationData = confBool("return.revocation.data", false);
    this.expectedFailure = confStr("expected.failure") != null ? confStr("expected.failure").toLowerCase()
            : null;
    this.running = false;

    final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

    final String[] chain = confStr("chain").toLowerCase().split(",");
    for (String certName : chain) {
        final String encodedCert = confStr("cert." + certName);
        final X509Certificate cert = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(encodedCert)));
        this.certChain.add(cert);
    }

    start();
    log("initialized");
}

From source file:org.simbasecurity.core.saml.UtilsTest.java

/**
 * Tests the validateSign method of the com.onelogin.saml.Utils
 *//*  ww w.j a  v  a2s. co  m*/
@Test
public void testValidateSign() throws Exception {
    String certificate = "MIICgTCCAeoCCQCbOlrWDdX7FTANBgkqhkiG9w0BAQUFADCBhDELMAkGA1UEBhMCTk8xGDAWBgNVBAgTD0FuZHJlYXM"
            + "gU29sYmVyZzEMMAoGA1UEBxMDRm9vMRAwDgYDVQQKEwdVTklORVRUMRgwFgYDVQQDEw9mZWlkZS5lcmxhbmcubm8xITA"
            + "fBgkqhkiG9w0BCQEWEmFuZHJlYXNAdW5pbmV0dC5ubzAeFw0wNzA2MTUxMjAxMzVaFw0wNzA4MTQxMjAxMzVaMIGEMQs"
            + "wCQYDVQQGEwJOTzEYMBYGA1UECBMPQW5kcmVhcyBTb2xiZXJnMQwwCgYDVQQHEwNGb28xEDAOBgNVBAoTB1VOSU5FVFQ"
            + "xGDAWBgNVBAMTD2ZlaWRlLmVybGFuZy5ubzEhMB8GCSqGSIb3DQEJARYSYW5kcmVhc0B1bmluZXR0Lm5vMIGfMA0GCSq"
            + "GSIb3DQEBAQUAA4GNADCBiQKBgQDivbhR7P516x/S3BqKxupQe0LONoliupiBOesCO3SHbDrl3+q9IbfnfmE04rNuMcP"
            + "sIxB161TdDpIesLCn7c8aPHISKOtPlAeTZSnb8QAu7aRjZq3+PbrP5uW3TcfCGPtKTytHOge/OlJbo078dVhXQ14d1ED"
            + "wXJW1rRXuUt4C8QIDAQABMA0GCSqGSIb3DQEBBQUAA4GBACDVfp86HObqY+e8BUoWQ9+VMQx1ASDohBjwOsg2WykUqRX"
            + "F+dLfcUH9dWR63CtZIKFDbStNomPnQz7nbK+onygwBspVEbnHuUihZq3ZUdmumQqCw4Uvs/1Uvq3orOo/WJVhTyvLgFV"
            + "K2QarQ4/67OZfHd7R+POBXhophSMv1ZOo";
    CertificateFactory fty = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(certificate.getBytes()));
    Certificate cert = fty.generateCertificate(bais);

    String responseCoded = getFile("responses/signed_message_response.xml.base64");
    Base64 base64 = new Base64();
    byte[] decodedB = base64.decode(responseCoded);
    String response = new String(decodedB);
    Document dom = Utils.loadXML(response);

    NodeList signatureResNodes = Utils.query(dom, "/samlp:Response/ds:Signature", null);
    assertThat(signatureResNodes.getLength()).isEqualTo(1);
    assertThat(Utils.validateSign(signatureResNodes.item(0), cert)).isTrue();

    assertThatThrownBy(() -> Utils.validateSign(dom.getChildNodes().item(0), cert))
            .isInstanceOf(MarshalException.class).hasMessageContaining("invalid Signature");

    responseCoded = getFile("responses/invalids/no_key.xml.base64");
    base64 = new Base64();
    decodedB = base64.decode(responseCoded);
    response = new String(decodedB);

    NodeList signatureNoKey = Utils.query(Utils.loadXML(response),
            "/samlp:Response/saml:Assertion/ds:Signature", null);
    assertThat(signatureNoKey.getLength()).isEqualTo(1);

    assertThatThrownBy(() -> Utils.validateSign(signatureNoKey.item(0), cert))
            .isInstanceOf(MarshalException.class);
}

From source file:com.vmware.identity.samlservice.impl.AuthnRequestStateTLSClientAuthenticationFilter.java

@Override
public void authenticate(AuthnRequestState t) throws SamlServiceException {
    log.debug("AuthnRequestStateTLSClientAuthenticationFilter.authenticate is called");

    Validate.notNull(t);/*from  ww  w . ja  va2s.  c o  m*/
    IdmAccessor accessor = t.getIdmAccessor();
    Validate.notNull(accessor);
    HttpServletRequest request = t.getRequest();
    Validate.notNull(request);
    AuthnRequest authnRequest = t.getAuthnRequest();
    Validate.notNull(authnRequest);

    PrincipalId principalId = null;

    X509Certificate certChain[] = null;

    //Get from the custom header first.
    String certStr = request.getHeader(AuthnRequestStateTLSClientAuthenticationFilter.clientCertHeader);

    if (certStr != null && certStr.length() > 0
            && request.getAuthType() == SecurityRequestWrapper.VMWARE_CLIENT_CERT_AUTH) {
        ByteArrayInputStream bais = null;
        CertificateFactory cf;
        try {
            cf = CertificateFactory.getInstance("X.509");
            bais = new ByteArrayInputStream(Base64.decode(certStr));
            X509Certificate cert = (X509Certificate) cf.generateCertificate(bais);
            certChain = new X509Certificate[] { cert };
        } catch (CertificateException e1) {
            log.error("Error reading client certificate from http header. ", e1);
            ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED,
                    WebSSOError.UNAUTHORIZED, WebSSOError.INVALID_CREDENTIAL);
            t.setValidationResult(vr);
            throw new SamlServiceException("Client Certificate error.", e1);
        }
    }

    // Get from standard place of sl client cert location
    if (certChain == null || certChain.length == 0) {
        certChain = (X509Certificate[]) request
                .getAttribute(AuthnRequestStateTLSClientAuthenticationFilter.clientCertAttributeName);
    }

    if (certChain == null || certChain.length == 0) {
        ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED,
                WebSSOError.UNAUTHORIZED, WebSSOError.NO_CLIENT_CERT);
        t.setValidationResult(vr);

    } else {
        try {
            principalId = accessor.authenticate(certChain);
            Validate.notNull(principalId, "principalId");
        } catch (Exception ex) {
            // could not authenticate with the certificate
            ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED,
                    WebSSOError.UNAUTHORIZED, WebSSOError.INVALID_CREDENTIAL);
            t.setValidationResult(vr);
        }
    }

    if (principalId != null) {
        t.setPrincipalId(principalId);
        t.setAuthnMethod(AuthnMethod.TLSCLIENT);
    }
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateManagementServiceImplTests.java

@Test(description = "This test case tests saving a list of Certificates in the keystore")
public void testSaveCertificate()
        throws CertificateManagementException, IOException, CertificateException, KeystoreException {
    File caCert = new File(CA_CERT_PEM);
    int before = managementService.getCertificates().size();
    byte[] caBytes = FileUtils.readFileToByteArray(caCert);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(caBytes));
    List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
    org.wso2.carbon.certificate.mgt.core.bean.Certificate certificateToStore = new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
    certificateToStore.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
    certificateToStore.setCertificate(cert);
    certificates.add(certificateToStore);
    managementService.saveCertificate(certificates);
    int after = managementService.getCertificates().size();
    Assert.assertEquals((before + 1), after);
    log.info("SaveCertificate Test Successful");
}

From source file:test.integ.be.fedict.trust.CodeSigningTest.java

@Test
public void testValidation2011_2014() throws Exception {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    InputStream fedictCertInputStream = CodeSigningTest.class.getResourceAsStream("/fedict-2011-2014.der");
    X509Certificate fedictCert = (X509Certificate) certificateFactory
            .generateCertificate(fedictCertInputStream);
    LOG.debug("code signing not before: " + fedictCert.getNotBefore());
    LOG.debug("code signing serial: " + fedictCert.getSerialNumber());

    InputStream govCertInputStream = CodeSigningTest.class.getResourceAsStream("/gov-ca-2011.der");
    X509Certificate govCert = (X509Certificate) certificateFactory.generateCertificate(govCertInputStream);

    InputStream rootCertInputStream = CodeSigningTest.class.getResourceAsStream("/root-ca2.der");
    X509Certificate rootCert = (X509Certificate) certificateFactory.generateCertificate(rootCertInputStream);

    InputStream gsCertInputStream = CodeSigningTest.class
            .getResourceAsStream("/be/fedict/trust/roots/globalsign-be.crt");
    X509Certificate gsCert = (X509Certificate) certificateFactory.generateCertificate(gsCertInputStream);

    List<X509Certificate> certChain = new LinkedList<>();
    certChain.add(fedictCert);//ww  w . j  a v a2 s  .  co m
    certChain.add(govCert);
    certChain.add(rootCert);
    certChain.add(gsCert);

    MemoryCertificateRepository certificateRepository = new MemoryCertificateRepository();
    certificateRepository.addTrustPoint(gsCert);
    TrustValidator trustValidator = new TrustValidator(certificateRepository);

    NetworkConfig networkConfig = new NetworkConfig("proxy.yourict.net", 8080);
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator(networkConfig);
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator, null, true);

    trustValidator.isTrusted(certChain);
}

From source file:test.integ.be.fedict.trust.CodeSigningTest.java

@Test
public void testEVZW() throws Exception {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    InputStream fedictCertInputStream = CodeSigningTest.class.getResourceAsStream("/evzw/www.egreffe.be.crt");
    X509Certificate fedictCert = (X509Certificate) certificateFactory
            .generateCertificate(fedictCertInputStream);
    LOG.debug("code signing not before: " + fedictCert.getNotBefore());

    InputStream govCertInputStream = CodeSigningTest.class.getResourceAsStream("/gov-ca-2011.der");
    X509Certificate govCert = (X509Certificate) certificateFactory.generateCertificate(govCertInputStream);

    InputStream rootCertInputStream = CodeSigningTest.class.getResourceAsStream("/root-ca2.der");
    X509Certificate rootCert = (X509Certificate) certificateFactory.generateCertificate(rootCertInputStream);

    InputStream gsCertInputStream = CodeSigningTest.class
            .getResourceAsStream("/be/fedict/trust/roots/globalsign-be.crt");
    X509Certificate gsCert = (X509Certificate) certificateFactory.generateCertificate(gsCertInputStream);

    List<X509Certificate> certChain = new LinkedList<>();
    certChain.add(fedictCert);/*from   w ww. j ava2s. c o m*/
    certChain.add(govCert);
    certChain.add(rootCert);
    certChain.add(gsCert);

    MemoryCertificateRepository certificateRepository = new MemoryCertificateRepository();
    certificateRepository.addTrustPoint(gsCert);
    TrustValidator trustValidator = new TrustValidator(certificateRepository);

    NetworkConfig networkConfig = new NetworkConfig("proxy.yourict.net", 8080);
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator(networkConfig);
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator, null, false);

    trustValidator.isTrusted(certChain);
}

From source file:test.integ.be.fedict.trust.CodeSigningTest.java

@Test
public void testCertipostCodeSigning() throws Exception {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    InputStream fedictCertInputStream = CodeSigningTest.class.getResourceAsStream("/FedICT-BE0367302178.cer");
    X509Certificate fedictCert = (X509Certificate) certificateFactory
            .generateCertificate(fedictCertInputStream);
    LOG.debug("code signing not before: " + fedictCert.getNotBefore());

    InputStream govCertInputStream = CodeSigningTest.class.getResourceAsStream("/NCA_WSOS.crt");
    X509Certificate ca2Cert = (X509Certificate) certificateFactory.generateCertificate(govCertInputStream);

    InputStream rootCertInputStream = CodeSigningTest.class.getResourceAsStream("/NCA.crt");
    X509Certificate rootCert = (X509Certificate) certificateFactory.generateCertificate(rootCertInputStream);

    InputStream gsCertInputStream = CodeSigningTest.class.getResourceAsStream("/GTE_ROOT.crt");
    X509Certificate gsCert = (X509Certificate) certificateFactory.generateCertificate(gsCertInputStream);

    List<X509Certificate> certChain = new LinkedList<>();
    certChain.add(fedictCert);/*  w w  w. j a  va 2 s.co  m*/
    certChain.add(ca2Cert);
    certChain.add(rootCert);
    certChain.add(gsCert);

    MemoryCertificateRepository certificateRepository = new MemoryCertificateRepository();
    certificateRepository.addTrustPoint(gsCert);
    TrustValidator trustValidator = new TrustValidator(certificateRepository);

    trustValidator.setAlgorithmPolicy(new AllowAllAlgorithmPolicy());

    NetworkConfig networkConfig = new NetworkConfig("proxy.yourict.net", 8080);
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator(networkConfig);
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator, null, false);

    trustValidator.isTrusted(certChain);
}

From source file:test.integ.be.fedict.trust.CodeSigningTest.java

@Test
public void testValidation2010_2011() throws Exception {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    InputStream fedictCertInputStream = CodeSigningTest.class.getResourceAsStream("/fedict-2010-2011.der");
    X509Certificate fedictCert = (X509Certificate) certificateFactory
            .generateCertificate(fedictCertInputStream);
    LOG.debug("code signing not before: " + fedictCert.getNotBefore());

    InputStream govCertInputStream = CodeSigningTest.class.getResourceAsStream("/gov-ca-2010.der");
    X509Certificate govCert = (X509Certificate) certificateFactory.generateCertificate(govCertInputStream);

    InputStream rootCertInputStream = CodeSigningTest.class.getResourceAsStream("/root-ca2.der");
    X509Certificate rootCert = (X509Certificate) certificateFactory.generateCertificate(rootCertInputStream);

    InputStream gsCertInputStream = CodeSigningTest.class
            .getResourceAsStream("/be/fedict/trust/roots/globalsign-be.crt");
    X509Certificate gsCert = (X509Certificate) certificateFactory.generateCertificate(gsCertInputStream);

    List<X509Certificate> certChain = new LinkedList<>();
    certChain.add(fedictCert);/*w  w  w .  j a  v a2  s .  com*/
    certChain.add(govCert);
    certChain.add(rootCert);
    certChain.add(gsCert);

    MemoryCertificateRepository certificateRepository = new MemoryCertificateRepository();
    certificateRepository.addTrustPoint(gsCert);
    TrustValidator trustValidator = new TrustValidator(certificateRepository);

    NetworkConfig networkConfig = new NetworkConfig("proxy.yourict.net", 8080);
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator(networkConfig);
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator, null, true);

    try {
        trustValidator.isTrusted(certChain);
        fail();
    } catch (TrustLinkerResultException e) {
        // expected
    }
}