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.codice.ddf.security.handler.pki.PKIHandlerTest.java

private X509Certificate[] getTestCerts() throws CertificateException {
    String certificateString = getTestCertString();

    InputStream stream = new ByteArrayInputStream(Base64.decodeBase64(certificateString.getBytes()));
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) factory.generateCertificate(stream);
    X509Certificate[] certs = new X509Certificate[1];
    certs[0] = cert;/*from  w w  w .  j  a  v  a 2s  .  co  m*/

    return certs;
}

From source file:be.e_contract.mycarenet.certra.CertRAClient.java

private byte[] getCmsData(byte[] cms) throws Exception {
    CMSSignedData cmsSignedData = new CMSSignedData(cms);
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next();
    SignerId signerId = signer.getSID();

    Store certificateStore = cmsSignedData.getCertificates();
    Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId);

    X509CertificateHolder certificateHolder = certificateCollection.iterator().next();
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));
    // we trust SSL here, no need for explicit verification of CMS signing
    // certificate

    LOG.debug("CMS signing certificate subject: " + certificate.getSubjectX500Principal());

    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(certificate);/*from w  w  w .  j  a  v a  2s .c  o m*/
    boolean signatureResult = signer.verify(signerInformationVerifier);
    if (false == signatureResult) {
        throw new SecurityException("woops");
    }

    CMSTypedData signedContent = cmsSignedData.getSignedContent();
    byte[] responseData = (byte[]) signedContent.getContent();

    return responseData;
}

From source file:be.e_contract.mycarenet.etee.Unsealer.java

private byte[] getVerifiedContent(byte[] cmsData)
        throws CertificateException, CMSException, IOException, OperatorCreationException {
    CMSSignedData cmsSignedData = new CMSSignedData(cmsData);
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next();
    SignerId signerId = signer.getSID();

    Store certificateStore = cmsSignedData.getCertificates();
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId);
    if (null == this.senderCertificate) {
        if (certificateCollection.isEmpty()) {
            throw new SecurityException("no sender certificate present");
        }//from  w w w .j av  a2  s  .  c o  m
        X509CertificateHolder certificateHolder = certificateCollection.iterator().next();
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));

        this.senderCertificate = certificate;
        LOG.debug("signer certificate subject: " + certificate.getSubjectX500Principal());
    }

    /*
     * By reusing the sender certificate we have the guarantee that the
     * outer signature and inner signature share the same origin.
     */
    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(this.senderCertificate);
    boolean signatureResult = signer.verify(signerInformationVerifier);
    if (false == signatureResult) {
        throw new SecurityException("woops");
    }

    CMSTypedData signedContent = cmsSignedData.getSignedContent();
    byte[] data = (byte[]) signedContent.getContent();
    return data;
}

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

@Test
public void testValidation() throws Exception {
    Proxy proxy = Proxy.NO_PROXY;
    // Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
    // "proxy.yourict.net", 8080));
    NetworkConfig networkConfig = null; // new
    // NetworkConfig("proxy.yourict.net",
    // 8080);//from   w ww. j  a  v  a 2s  .c o  m
    // URL url = new URL("https://eid.belgium.be/"); // OK
    // URL url = new URL("https://www.fortisbanking.be"); // OK
    // URL url = new URL("https://www.e-contract.be/"); // OK
    // URL url = new URL("https://idp.services.belgium.be"); // OK
    // URL url = new URL("https://idp.int.belgium.be"); // OK
    //URL url = new URL("https://test.eid.belgium.be/");
    URL url = new URL("https://www.cloudflare.com/");

    // URL url = new URL("https://www.facebook.com");
    // URL url = new URL("https://www.twitter.com");
    // URL url = new URL("https://www.mozilla.org");
    // URL url = new URL("https://www.verisign.com/");
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(proxy);
    connection.connect();
    Certificate[] serverCertificates = connection.getServerCertificates();
    List<X509Certificate> certificateChain = new LinkedList<>();
    for (Certificate certificate : serverCertificates) {
        X509Certificate x509Cert = (X509Certificate) certificate;
        certificateChain.add(x509Cert);
        LOG.debug("certificate subject: " + x509Cert.getSubjectX500Principal());
        LOG.debug("certificate issuer: " + x509Cert.getIssuerX500Principal());
    }

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate rootCertificate = (X509Certificate) certificateFactory.generateCertificate(
            SSLTrustValidatorTest.class.getResourceAsStream("/ecc/AddTrustExternalCARoot.crt"));
    certificateChain.add(rootCertificate);

    MemoryCertificateRepository certificateRepository = new MemoryCertificateRepository();
    certificateRepository.addTrustPoint(certificateChain.get(certificateChain.size() - 1));

    //certificateRepository.addTrustPoint(rootCertificate);
    TrustValidator trustValidator = new TrustValidator(certificateRepository);
    trustValidator.setAlgorithmPolicy(new AlgorithmPolicy() {

        @Override
        public void checkSignatureAlgorithm(String signatureAlgorithm, Date validationDate)
                throws SignatureException {
            LOG.debug("signature algo: " + signatureAlgorithm);
            // allow all
        }
    });

    // next is kind of a default trust linked pattern.
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator(networkConfig);
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator);

    // operate
    trustValidator.isTrusted(certificateChain);
}

From source file:org.jvnet.hudson.update_center.Signing.java

/**
* Loads a certificate chain and makes sure it's valid.
*///  w  w w  . j ava  2 s  .  co  m
private List<X509Certificate> getCertificateChain() throws FileNotFoundException, GeneralSecurityException {
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    for (File f : certificates) {
        X509Certificate c = (X509Certificate) cf.generateCertificate(new FileInputStream(f));
        c.checkValidity();
        certs.add(c);
    }

    Set<TrustAnchor> rootCAs = CertificateUtil.getDefaultRootCAs();
    rootCAs.add(new TrustAnchor(
            (X509Certificate) cf.generateCertificate(getClass().getResourceAsStream("/hudson-community.cert")),
            null));

    try {
        CertificateUtil.validatePath(certs, rootCAs);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }
    return certs;
}

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

private Certificate loadCertificate() throws CertificateException {
    String certificate = configurationService.getValue(SimbaConfigurationParameter.SAML_IDP_CERTIFICATE);
    CertificateFactory fty = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(certificate.getBytes()));
    return fty.generateCertificate(bais);
}

From source file:be.e_contract.mycarenet.etee.EncryptionToken.java

private X509Certificate parseEncryptionCertificate(byte[] encodedEncryptionToken)
        throws CMSException, CertificateException, IOException, OperatorCreationException {
    CMSSignedData cmsSignedData = new CMSSignedData(encodedEncryptionToken);

    // get signer identifier
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next();
    SignerId signerId = signer.getSID();

    // get signer certificate
    Store certificateStore = cmsSignedData.getCertificates();
    LOG.debug("certificate store type: " + certificateStore.getClass().getName());
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> signingCertificateCollection = certificateStore.getMatches(signerId);
    X509CertificateHolder signingCertificateHolder = signingCertificateCollection.iterator().next();
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate signingCertificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(signingCertificateHolder.getEncoded()));
    LOG.debug("signing certificate: " + signingCertificate.getSubjectX500Principal());

    // verify CMS signature
    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(signingCertificate);//  ww  w. j a  v a 2s .c  om
    boolean signatureResult = signer.verify(signerInformationVerifier);
    if (false == signatureResult) {
        throw new SecurityException("ETK signature invalid");
    }

    // get encryption certificate
    CMSTypedData signedContent = cmsSignedData.getSignedContent();
    byte[] data = (byte[]) signedContent.getContent();
    X509Certificate encryptionCertificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(data));

    LOG.debug("all available certificates:");
    logCertificates(certificateStore, null);

    // get authentication certificate
    CustomSelector authenticationSelector = new CustomSelector();
    authenticationSelector.setSubject(encryptionCertificate.getIssuerX500Principal());
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> authenticationCertificates = certificateStore
            .getMatches(authenticationSelector);
    if (authenticationCertificates.size() != 1) {
        LOG.debug("no authentication certificate match");
    }
    X509CertificateHolder authenticationCertificateHolder = authenticationCertificates.iterator().next();
    this.authenticationCertificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(authenticationCertificateHolder.getEncoded()));

    verifyProxyCertificate(encryptionCertificate, this.authenticationCertificate);

    return encryptionCertificate;
}

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

/**
 * Returns the generated certifcate.//from w w w.j ava  2 s.  c om
 */
public X509Certificate getCertificate() {
    CertificateFactory cf = CertTools.getCertificateFactory();
    X509Certificate cert = null;
    try {
        String certStr = (String) data.get(CERTIFICATE);
        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: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());
    }//  w w  w .  j av a 2 s  .  com
}

From source file:com.brienwheeler.apps.tomcat.TomcatBean.java

private X509Certificate readCertFile() throws IOException, CertificateException {
    String parse[] = readPEMFile(sslCertFile, CERT_PATTERN, 1);
    if (parse == null)
        throw new IllegalArgumentException("invalid certificate file contents");
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    return (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(Base64.decode(parse[0])));
}