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:test.unit.be.e_contract.mycarenet.etee.SealTest.java

@Test
public void testSeal() throws Exception {
    InputStream sealInputStream = SealTest.class.getResourceAsStream("/seal-fcorneli.der");
    assertNotNull(sealInputStream);/* w w  w  .  ja  v  a 2 s.c o  m*/

    // check outer signature

    CMSSignedData cmsSignedData = new CMSSignedData(sealInputStream);
    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);
    X509CertificateHolder certificateHolder = certificateCollection.iterator().next();
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));

    Security.addProvider(new BouncyCastleProvider());
    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(certificate);
    boolean signatureResult = signer.verify(signerInformationVerifier);
    assertTrue(signatureResult);

    LOG.debug("signer certificate: " + certificate);

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

    // decrypt content

    CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser(data);
    LOG.debug("content encryption algo: "
            + cmsEnvelopedDataParser.getContentEncryptionAlgorithm().getAlgorithm().getId());

    RecipientInformationStore recipientInformationStore = cmsEnvelopedDataParser.getRecipientInfos();
    @SuppressWarnings("unchecked")
    Collection<RecipientInformation> recipients = recipientInformationStore.getRecipients();
    RecipientInformation recipientInformation = recipients.iterator().next();
    LOG.debug("recipient info type: " + recipientInformation.getClass().getName());
    KeyTransRecipientInformation keyTransRecipientInformation = (KeyTransRecipientInformation) recipientInformation;

}

From source file:net.ripe.rpki.commons.crypto.x509cert.X509CertificateParser.java

private void parse() {
    try {// www. ja v  a 2s. c om
        final Closer closer = Closer.create();
        try {
            final InputStream input = closer.register(new ByteArrayInputStream(encoded));
            final CertificateFactory factory = CertificateFactory.getInstance("X.509");
            certificate = (X509Certificate) factory.generateCertificate(input);
        } catch (final CertificateException e) {
            certificate = null;
        } catch (final Throwable t) {
            throw closer.rethrow(t);
        } finally {
            closer.close();
        }
    } catch (final IOException e) {
        certificate = null;
    }
    result.rejectIfNull(certificate, CERTIFICATE_PARSED);
}

From source file:org.ejbca.util.keystore.KeyTools.java

/**
 * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is
 * set to 'privateKey' and the private key password is null.
 *
 * @param alias the alias used for the key entry
 * @param privKey RSA private key/* w ww  .j  a  v  a 2 s  . co m*/
 * @param cert user certificate
 * @param cachain CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * @return KeyStore containing PKCS12-keystore
 * @exception Exception if input parameters are not OK or certificate generation fails
 */
public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert,
        final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (log.isTraceEnabled()) {
        log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    final Certificate[] chain = new Certificate[len];
    // To not get a ClassCastException we need to generate a real new certificate with BC
    final CertificateFactory cf = CertTools.getCertificateFactory();
    chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));

    if (cachain != null) {
        for (int i = 0; i < cachain.length; i++) {
            final X509Certificate tmpcert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded()));
            chain[i + 1] = tmpcert;
        }
    }
    if (chain.length > 1) {
        for (int i = 1; i < chain.length; i++) {
            final X509Certificate cacert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded()));
            // Set attributes on CA-cert
            try {
                final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i];
                // We construct a friendly name for the CA, and try with some parts from the DN if they exist.
                String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN");
                // On the ones below we +i to make it unique, O might not be otherwise
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O") + i;
                }
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU" + i);
                }
                if (cafriendly == null) {
                    cafriendly = "CA_unknown" + i;
                }
                caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                        new DERBMPString(cafriendly));
            } catch (ClassCastException e) {
                log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
            }
        }
    }

    // Set attributes on user-cert
    try {
        final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0];
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        // in this case we just set the local key id to that of the public key
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // "Clean" private key, i.e. remove any old attributes
    final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC");
    final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));
    // Set attributes for private key
    try {
        final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk;
        // in this case we just set the local key id to that of the public key
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // store the key and the certificate chain
    final KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    store.load(null, null);
    store.setKeyEntry(alias, pk, null, chain);
    if (log.isTraceEnabled()) {
        log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    return store;
}

From source file:com.vmware.identity.openidconnect.client.AuthenticationFrameworkHelper.java

private X509Certificate convertToX509Certificate(String base64PEMCertificate) throws OIDCClientException {
    X509Certificate x509Certificate = null;
    InputStream is = new ByteArrayInputStream(Base64.decodeBase64(base64PEMCertificate.getBytes()));
    CertificateFactory cf;
    try {/*from  w  ww  .j a  v a 2  s  .co m*/
        cf = CertificateFactory.getInstance("X509");
        x509Certificate = (X509Certificate) cf.generateCertificate(is);
    } catch (CertificateException e) {
        throw new OIDCClientException("Failed to convert to X509 certificate: " + e.getMessage(), e);
    }
    return x509Certificate;
}

From source file:com.shekhargulati.reactivex.docker.client.ssl.DockerCertificates.java

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new DockerCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }/*from   w ww  .j a v a 2  s .  com*/

    try {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, KEY_STORE_PASSWORD);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException
            | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw new DockerCertificateException(e);
    }
}

From source file:com.shekhargulati.reactivex.rxokhttp.SslCertificates.java

private SslCertificates(final Builder builder) throws SslCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new SslCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }// w  ww.  j  a  v a 2  s  .  c om

    try {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, KEY_STORE_PASSWORD);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (java.security.cert.CertificateException | IOException | NoSuchAlgorithmException
            | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException
            | KeyManagementException e) {
        throw new SslCertificateException(e);
    }
}

From source file:test.unit.be.fedict.trust.MemoryCertificateRepositoryTest.java

@Test
public void trustPointFoundByDifferentCryptoProvider() throws Exception {

    // setup/*from  w w w.  j  a v a2  s .c o  m*/
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    KeyPair keyPair = TrustTestUtils.generateKeyPair();
    X509Certificate trustPoint = TrustTestUtils.generateSelfSignedCertificate(keyPair, "CN=Test", notBefore,
            notAfter);
    LOG.debug("trust point certificate impl class: " + trustPoint.getClass().getName());

    MemoryCertificateRepository testedInstance = new MemoryCertificateRepository();
    testedInstance.addTrustPoint(trustPoint);

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", new BouncyCastleProvider());
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(trustPoint.getEncoded()));
    LOG.debug("certificate impl class: " + certificate.getClass().getName());

    // operate
    assertFalse(certificate.getClass().equals(trustPoint.getClass()));
    assertTrue(testedInstance.isTrustPoint(certificate));
}

From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateJWTConfig.java

/**
 * The public key used to verify the signatures of JWT tokens.
 *
 * @param keyValue The string of the public key to use in either RSA or X.509 format
 * @return A public key object to use when validating JWT tokens
 * @throws IOException             On reading or closing byte array input stream
 * @throws JoseException           When trying to create the key using jose library
 * @throws InvalidKeySpecException When the cert has an invalid spec
 * @throws CertificateException    When trying to create a X.509 specification object
 *//*from  w  ww .  ja v a  2  s  .c  om*/
@Bean
public PublicKey jwtPublicKey(
        @Value("${genie.security.oauth2.pingfederate.jwt.keyValue}") final String keyValue)
        throws IOException, JoseException, InvalidKeySpecException, CertificateException {
    final String certBegin = "-----BEGIN CERTIFICATE-----";
    final String rsaBegin = "-----BEGIN PUBLIC KEY-----";
    if (StringUtils.isEmpty(keyValue)) {
        // In future try a key resolver to pull the key from the server
        throw new IllegalArgumentException("No value set for security.oauth2.resource.jwt.keyValue");
    }

    if (keyValue.startsWith(certBegin)) {
        // X.509 cert
        try (final ByteArrayInputStream bis = new ByteArrayInputStream(keyValue.getBytes("UTF-8"))) {
            final CertificateFactory fact = CertificateFactory.getInstance("X.509");
            final X509Certificate cer = (X509Certificate) fact.generateCertificate(bis);
            return cer.getPublicKey();
        }
    } else if (keyValue.startsWith(rsaBegin)) {
        // RSA Public Key
        return new RsaKeyUtil().fromPemEncoded(keyValue);
    } else {
        throw new IllegalArgumentException(
                "Only support X.509 pem certs or Public RSA Keys for security.oauth2.resource.jwt.keyValue");
    }
}

From source file:com.netflix.genie.security.oauth2.pingfederate.PingFederateJWTConfig.java

/**
 * The public key used to verify the signatures of JWT tokens.
 *
 * @param keyValue The string of the public key to use in either RSA or X.509 format
 * @return A public key object to use when validating JWT tokens
 * @throws IOException             On reading or closing byte array input stream
 * @throws JoseException           When trying to create the key using jose library
 * @throws InvalidKeySpecException When the cert has an invalid spec
 * @throws CertificateException    When trying to create a X.509 specification object
 *//*from  w ww  .  jav  a 2s  .c o  m*/
@Bean
public PublicKey jwtPublicKey(
        @Value("${genie.security.oauth2.pingfederate.jwt.keyValue}") final String keyValue)
        throws IOException, JoseException, InvalidKeySpecException, CertificateException {
    final String certBegin = "-----BEGIN CERTIFICATE-----";
    final String rsaBegin = "-----BEGIN PUBLIC KEY-----";
    if (StringUtils.isEmpty(keyValue)) {
        // In future try a key resolver to pull the key from the server
        throw new IllegalArgumentException("No value set for security.oauth2.resource.jwt.keyValue");
    }

    if (keyValue.startsWith(certBegin)) {
        // X.509 cert
        try (ByteArrayInputStream bis = new ByteArrayInputStream(keyValue.getBytes("UTF-8"))) {
            final CertificateFactory fact = CertificateFactory.getInstance("X.509");
            final X509Certificate cer = (X509Certificate) fact.generateCertificate(bis);
            return cer.getPublicKey();
        }
    } else if (keyValue.startsWith(rsaBegin)) {
        // RSA Public Key
        return new RsaKeyUtil().fromPemEncoded(keyValue);
    } else {
        throw new IllegalArgumentException(
                "Only support X.509 pem certs or Public RSA Keys for security.oauth2.resource.jwt.keyValue");
    }
}

From source file:org.security4java.X509CertificateRetrieverImpl.java

public X509Certificate getClientCertificate(HttpServletRequest request) {
    X509Certificate ret = null;//from   w  ww.j  av  a2s . co m
    if (logger.isDebugEnabled()) {
        logger.debug("getClientCertificate(HttpServletRequest) - start");
    }

    Object attribute = request.getAttribute(certAttrName);
    if (attribute instanceof X509Certificate[]) {
        X509Certificate[] certs = (X509Certificate[]) attribute;
        if (certs != null && certs.length > 0) {
            ret = certs[0];
            if (logger.isDebugEnabled()) {
                logger.debug("Success to get ClientCertificate [" + ret + "].");
            }
        }
    } else if (attribute instanceof String) {
        if (logger.isDebugEnabled()) {
            logger.debug("Received a String. Try to convert the string [" + attribute + "] into certificate.");
        }
        String certificateString = (String) attribute;
        byte[] certificateData = certificateString.getBytes();
        ByteArrayInputStream certificateInputStream = new ByteArrayInputStream(certificateData);
        X509Certificate certificates[] = null;
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate x509Certificate = (X509Certificate) certificateFactory
                    .generateCertificate(certificateInputStream);
            certificates = new X509Certificate[1];
            certificates[0] = x509Certificate;
            ret = certificates[0];
            if (logger.isDebugEnabled()) {
                logger.debug("Success to convert string to client certificate [" + ret + "].");
            }
        } catch (CertificateException e) {
            logger.info("Failed to convert the string into certificate [" + attribute + "]. " + e.getMessage());
        }
    } else if (logger.isDebugEnabled()) {
        logger.debug("No client certificate found in the request.");
    }

    return ret;
}