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:eu.stork.peps.auth.engine.core.impl.SignP12.java

/**
 * Validate signature.//from w  ww . j av  a  2  s.  co m
 * 
 * @param tokenSaml token SAML
 * 
 * @return the SAMLObject validated.
 * 
 * @throws SAMLEngineException error validate signature
 * 
 */
@Override
public SAMLObject validateSignature(final SignableSAMLObject tokenSaml) throws SAMLEngineException {
    LOG.info("Start signature validation.");
    try {

        // Validate structure signature
        final SAMLSignatureProfileValidator sigProfValidator = new SAMLSignatureProfileValidator();
        try {
            // Indicates signature id conform to SAML Signature profile
            sigProfValidator.validate(tokenSaml.getSignature());
        } catch (ValidationException e) {
            LOG.error("ValidationException: signature isn't conform to SAML Signature profile.");
            throw new SAMLEngineException(e);
        }

        String aliasCert = null;
        X509Certificate certificate;

        final List<Credential> trustCred = new ArrayList<Credential>();

        for (final Enumeration<String> e = trustStore.aliases(); e.hasMoreElements();) {
            aliasCert = e.nextElement();
            final BasicX509Credential credential = new BasicX509Credential();
            certificate = (X509Certificate) trustStore.getCertificate(aliasCert);
            credential.setEntityCertificate(certificate);
            trustCred.add(credential);
        }

        final KeyInfo keyInfo = tokenSaml.getSignature().getKeyInfo();

        final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0)
                .getX509Certificates().get(0);

        final CertificateFactory certFact = CertificateFactory.getInstance("X.509");
        final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));
        final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);

        // Exist only one certificate
        final BasicX509Credential entityX509Cred = new BasicX509Credential();
        entityX509Cred.setEntityCertificate(cert);

        /* A better use of PKI based validation but not wanted for STORK...
        boolean trusted = false;
                
        for (final Enumeration<String> e = trustStore.aliases(); e.hasMoreElements();) 
        {
           aliasCert = e.nextElement();      
           certificate = (X509Certificate) trustStore.getCertificate(aliasCert);               
           try {
              cert.verify(certificate.getPublicKey());
              trusted = true;
              break;
           }
           catch (Exception ex) {
              //Do nothing - cert not trusted yet
           }
        }
                
        if (!trusted)
           throw new SAMLEngineException("Certificate is not trusted.");*/

        // Validate trust certificates
        final ExplicitKeyTrustEvaluator keyTrustEvaluator = new ExplicitKeyTrustEvaluator();
        if (!keyTrustEvaluator.validate(entityX509Cred, trustCred)) {
            throw new SAMLEngineException("Certificate it is not trusted.");
        }

        // Validate signature
        final SignatureValidator sigValidator = new SignatureValidator(entityX509Cred);
        sigValidator.validate(tokenSaml.getSignature());

    } catch (ValidationException e) {
        LOG.error("ValidationException.");
        throw new SAMLEngineException(e);
    } catch (KeyStoreException e) {
        LOG.error("KeyStoreException.", e);
        throw new SAMLEngineException(e);
    } catch (GeneralSecurityException e) {
        LOG.error("GeneralSecurityException.", e);
        throw new SAMLEngineException(e);
    }
    return tokenSaml;
}

From source file:test.unit.test.be.fedict.eid.applet.model.XmlSignatureServiceBeanTest.java

private X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, DateTime notBefore,
        DateTime notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean caFlag,
        int pathLength, String ocspUri, KeyUsage keyUsage) throws IOException, InvalidKeyException,
        IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException {
    String signatureAlgorithm = "SHA1withRSA";
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.reset();//from ww w .  java2  s.  c om
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setSignatureAlgorithm(signatureAlgorithm);
    certificateGenerator.setNotBefore(notBefore.toDate());
    certificateGenerator.setNotAfter(notAfter.toDate());
    X509Principal issuerDN;
    if (null != issuerCertificate) {
        issuerDN = new X509Principal(issuerCertificate.getSubjectX500Principal().toString());
    } else {
        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));

    if (caFlag) {
        if (-1 == pathLength) {
            certificateGenerator.addExtension(X509Extensions.BasicConstraints, false,
                    new BasicConstraints(true));
        } else {
            certificateGenerator.addExtension(X509Extensions.BasicConstraints, false,
                    new BasicConstraints(pathLength));
        }
    }

    if (null != ocspUri) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        certificateGenerator.addExtension(X509Extensions.AuthorityInfoAccess.getId(), false,
                authorityInformationAccess);
    }

    if (null != keyUsage) {
        certificateGenerator.addExtension(X509Extensions.KeyUsage, true, keyUsage);
    }

    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:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

public X509Certificate pemToX509Certificate(String pem) throws KeystoreException {
    InputStream inputStream = null;
    X509Certificate x509Certificate = null;
    try {//from   w ww.j  av a  2s  . c o  m

        inputStream = new ByteArrayInputStream(Base64.decodeBase64(pem.getBytes()));
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        x509Certificate = (X509Certificate) cf.generateCertificate(inputStream);

    } catch (CertificateException e) {
        String errorMsg = "Certificate issue occurred when generating converting PEM to x509Certificate";
        log.error(errorMsg, e);
        throw new KeystoreException(errorMsg, e);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            log.error("Error closing Certificate input stream", e);
        }
    }
    return x509Certificate;
}

From source file:ee.sk.digidoc.SignedDoc.java

/**
 * Reads X509 certificate from a data stream
 * @param data input data in Base64 form
 * @return X509Certificate object//from w  w  w. j  av  a  2s  .  co m
 * @throws EFormException for all errors
 */
public static X509Certificate readCertificate(byte[] data) throws DigiDocException {
    X509Certificate cert = null;
    try {
        ByteArrayInputStream certStream = new ByteArrayInputStream(data);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(certStream);
        certStream.close();
    } catch (Exception ex) {
        m_logger.error("Error reading certificate: " + ex);
        //DigiDocException.handleException(ex, DigiDocException.ERR_READ_CERT);
        return null;
    }
    return cert;
}

From source file:ee.sk.digidoc.SignedDoc.java

/**
 * Reads the cert from a file/* w ww  .  j  a  va 2s. co m*/
 * @param certFile certificates file name
 * @return certificate object
 */
public static X509Certificate readCertificate(File certFile) throws DigiDocException {
    X509Certificate cert = null;
    try {
        FileInputStream fis = new FileInputStream(certFile);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) certificateFactory.generateCertificate(fis);
        fis.close();
        //byte[] data = readFile(certFile);
        //cert = readCertificate(data);
    } catch (Exception ex) {
        DigiDocException.handleException(ex, DigiDocException.ERR_READ_FILE);
    }
    return cert;
}

From source file:nl.nikhef.eduroam.WiFiEduroam.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private void applyAndroid43EnterpriseSettings(WifiConfiguration currentConfig,
        HashMap<String, String> configMap) {
    try {//ww w  .  java  2s  . co m
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(
                Base64.decode(certificate.replaceAll("-----(BEGIN|END) CERTIFICATE-----", "")));
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
        in = new ByteArrayInputStream(Base64.decode(ca.replaceAll("-----(BEGIN|END) CERTIFICATE-----", "")));
        X509Certificate caCert = (X509Certificate) certFactory.generateCertificate(in);

        WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
        enterpriseConfig.setPhase2Method(Phase2.NONE);
        enterpriseConfig.setAnonymousIdentity(configMap.get(INT_ANONYMOUS_IDENTITY));
        enterpriseConfig.setEapMethod(Eap.TLS);

        enterpriseConfig.setCaCertificate(caCert);
        enterpriseConfig.setClientKeyEntry(this.csr.getPrivate(), cert);
        enterpriseConfig.setIdentity(configMap.get(INT_ANONYMOUS_IDENTITY));
        enterpriseConfig.setSubjectMatch(configMap.get(INT_SUBJECT_MATCH));
        currentConfig.enterpriseConfig = enterpriseConfig;

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:view.CertificateManagementDialog.java

public Certificate readCertificateFromFile(File f) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
    Certificate cert = null;// ww w . ja va 2  s  .  c  o m
    while (in.available() > 0) {
        cert = cf.generateCertificate(in);
    }
    in.close();
    return cert;
}

From source file:ee.sk.digidoc.SignedDoc.java

/**
 * Reads the cert from a file, URL or from another
 * location somewhere in the CLASSPATH such as
 * in the librarys jar file.//from   w w  w .j a  va2 s  .  c  o m
 * @param certLocation certificates file name,
 * or URL. You can use url in form jar://<location> to read
 * a certificate from the car file or some other location in the
 * CLASSPATH
 * @return certificate object
 */
public static X509Certificate readCertificate(String certLocation) throws DigiDocException {
    X509Certificate cert = null;
    InputStream isCert = null;
    try {
        URL url = null;
        if (certLocation.startsWith("http")) {
            url = new URL(certLocation);
            isCert = url.openStream();
        } else if (certLocation.startsWith("jar://")) {
            ClassLoader cl = ConfigManager.instance().getClass().getClassLoader();
            isCert = cl.getResourceAsStream(certLocation.substring(6));
        } else {
            isCert = new FileInputStream(certLocation);
        }
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) certificateFactory.generateCertificate(isCert);
        isCert.close();
        isCert = null;
    } catch (Exception ex) {
        DigiDocException.handleException(ex, DigiDocException.ERR_READ_FILE);
    } finally {
        if (isCert != null) {
            try {
                isCert.close();
            } catch (Exception ex2) {
                m_logger.error("Error closing streams: " + ex2);
            }
        }
    }
    return cert;
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName, String path, String storepass, KeyStore store)
        throws KeystoreEditorException {
    OutputStream fos = null;// w w  w  .j a  va  2s.c  o  m
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }
        Path storeFile = Paths.get(path);
        //check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            //priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            //java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();

            //we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();

                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }

            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //need to parse der separately from pem, der has the same mime type but is binary hence checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(
                                jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }

                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    Certificate certificate = certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate)
                            .getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(),
                                    keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(),
                                    chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.error(
                                    "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.",
                                    e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}

From source file:org.teiid.resource.adapter.ftp.FtpManagedConnectionFactory.java

public void setCertificate(String certificate) {
    this.certificate = certificate;
    if (this.certificate != null && Files.exists(Paths.get(this.certificate))) {
        try {/*from  w ww  .  j ava  2  s. co  m*/
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); //$NON-NLS-1$
            InputStream in = Files.newInputStream(Paths.get(this.certificate));
            Certificate cert = certificateFactory.generateCertificate(in);
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            keyStore.setCertificateEntry("alias", cert); //$NON-NLS-1$
            trustManager = TrustManagerUtils.getDefaultTrustManager(keyStore);
        } catch (IOException | GeneralSecurityException e) {
            throw new TeiidRuntimeException(UTIL.getString("ftp_certificate_path", certificate, e)); //$NON-NLS-1$
        }
    }
}