Example usage for java.security.cert CertificateFactory getInstance

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

Introduction

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

Prototype

public static final CertificateFactory getInstance(String type) throws CertificateException 

Source Link

Document

Returns a certificate factory object that implements the specified certificate type.

Usage

From source file:com.wwpass.connection.WWPassConnection.java

private static X509Certificate readCertificate(String certFile) throws IOException, GeneralSecurityException {
    X509Certificate cert = null;/*  w  ww. java2s .  c  om*/
    FileInputStream certInput = new FileInputStream(certFile);
    try {
        cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(certInput);
    } finally {
        certInput.close();
    }

    return cert;
}

From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java

public X509Certificate getCertFromString(String certificateHeader) {
    CertificateFactory certificateFactory;
    try {//from   w  ww. ja v  a  2s  . co  m
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        log.error("Exception while creating CertificateFactory", e);
        return null;
    }

    // nginx forwards the certificate in a header by replacing new lines with whitespaces
    // (2 or more). Also replace tabs, which nginx sometimes sends instead of whitespaces.
    String certificateContent = certificateHeader.replaceAll("\\s{2,}", System.lineSeparator())
            .replaceAll("\\t+", System.lineSeparator());
    if (certificateContent == null || certificateContent.length() < 10) {
        log.debug("No certificate content found");
        return null;
    }
    X509Certificate userCertificate;
    try {
        userCertificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(certificateContent.getBytes("ISO-8859-11")));
    } catch (CertificateException | UnsupportedEncodingException e) {
        log.error("Exception while converting certificate extracted from header", e);
        return null;
    }
    log.debug("Certificate was extracted from the header");
    return userCertificate;
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

private String revokeInternal(User revoker, Enrollment enrollment, String reason, boolean genCRL)
        throws RevocationException, InvalidArgumentException {

    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set.");
    }/* w w  w  .jav  a  2 s  .c o m*/

    if (enrollment == null) {
        throw new InvalidArgumentException("revokee enrollment is not set");
    }
    if (revoker == null) {
        throw new InvalidArgumentException("revoker is not set");
    }

    logger.debug(format("revoke revoker: %s, reason: %s, url: %s", revoker.getName(), reason, url));

    try {
        setUpSSL();

        // get cert from to-be-revoked enrollment
        BufferedInputStream pem = new BufferedInputStream(
                new ByteArrayInputStream(enrollment.getCert().getBytes()));
        CertificateFactory certFactory = CertificateFactory
                .getInstance(Config.getConfig().getCertificateFormat());
        X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(pem);

        // get its serial number
        String serial = DatatypeConverter.printHexBinary(certificate.getSerialNumber().toByteArray());

        // get its aki
        // 2.5.29.35 : AuthorityKeyIdentifier
        byte[] extensionValue = certificate.getExtensionValue(Extension.authorityKeyIdentifier.getId());
        ASN1OctetString akiOc = ASN1OctetString.getInstance(extensionValue);
        String aki = DatatypeConverter
                .printHexBinary(AuthorityKeyIdentifier.getInstance(akiOc.getOctets()).getKeyIdentifier());

        // build request body
        RevocationRequest req = new RevocationRequest(caName, null, serial, aki, reason, genCRL);
        String body = req.toJson();

        // send revoke request
        JsonObject resp = httpPost(url + HFCA_REVOKE, body, revoker);
        logger.debug("revoke done");

        if (genCRL) {
            if (resp.isEmpty()) {
                throw new RevocationException("Failed to return CRL, revoke response is empty");
            }
            if (resp.isNull("CRL")) {
                throw new RevocationException("Failed to return CRL");
            }
            return resp.getString("CRL");
        }
        return null;
    } catch (CertificateException e) {
        logger.error("Cannot validate certificate. Error is: " + e.getMessage());
        throw new RevocationException("Error while revoking cert. " + e.getMessage(), e);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new RevocationException("Error while revoking the user. " + e.getMessage(), e);

    }
}

From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java

public X509TrustManager getTrustManager(final Iterable<String> identitiesToTest,
        final CertificateMatcher clientVerifier, final CertificateMatcher serverVerifier)
        throws GeneralSecurityException {
    // obtain the default X509 trust manager
    X509TrustManager defaultTm = null;
    TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    //workaround for https://bugs.openjdk.java.net/browse/JDK-6672015
    KeyStore ks = null;//from   w w w. j a va2s  .  c om
    String tsType = System.getProperty("javax.net.ssl.trustStoreType", null);
    if ("Windows-ROOT".equals(tsType)) {
        try {
            ks = KeyStore.getInstance(tsType);
            ks.load(null, null);
            int numEntries = keyStoreAppendIndex(ks);
            logger.info(
                    "Using Windows-ROOT. Aliases sucessfully renamed on " + numEntries + " root certificates.");
        } catch (Exception e) {
            logger.error("Could not rename Windows-ROOT aliases", e);
        }
    }

    tmFactory.init(ks);
    for (TrustManager m : tmFactory.getTrustManagers()) {
        if (m instanceof X509TrustManager) {
            defaultTm = (X509TrustManager) m;
            break;
        }
    }
    if (defaultTm == null)
        throw new GeneralSecurityException("No default X509 trust manager found");

    final X509TrustManager tm = defaultTm;

    return new X509TrustManager() {
        private boolean serverCheck;

        public X509Certificate[] getAcceptedIssuers() {
            return tm.getAcceptedIssuers();
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            serverCheck = true;
            checkCertTrusted(chain, authType);
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            serverCheck = false;
            checkCertTrusted(chain, authType);
        }

        private void checkCertTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // check and default configurations for property
            // if missing default is null - false
            String defaultAlwaysTrustMode = CertificateVerificationActivator.getResources()
                    .getSettingsString(CertificateService.PNAME_ALWAYS_TRUST);

            if (config.getBoolean(PNAME_ALWAYS_TRUST, Boolean.parseBoolean(defaultAlwaysTrustMode)))
                return;

            try {
                // check the certificate itself (issuer, validity)
                try {
                    chain = tryBuildChain(chain);
                } catch (Exception e) {
                } // don't care and take the chain as is

                if (serverCheck)
                    tm.checkServerTrusted(chain, authType);
                else
                    tm.checkClientTrusted(chain, authType);

                if (identitiesToTest == null || !identitiesToTest.iterator().hasNext())
                    return;
                else if (serverCheck)
                    serverVerifier.verify(identitiesToTest, chain[0]);
                else
                    clientVerifier.verify(identitiesToTest, chain[0]);

                // ok, globally valid cert
            } catch (CertificateException e) {
                String thumbprint = getThumbprint(chain[0], THUMBPRINT_HASH_ALGORITHM);
                String message = null;
                List<String> propNames = new LinkedList<String>();
                List<String> storedCerts = new LinkedList<String>();
                String appName = R.getSettingsString("service.gui.APPLICATION_NAME");

                if (identitiesToTest == null || !identitiesToTest.iterator().hasNext()) {
                    String propName = PNAME_CERT_TRUST_PREFIX + ".server." + thumbprint;
                    propNames.add(propName);

                    message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT_NOHOST",
                            new String[] { appName });

                    // get the thumbprints from the permanent allowances
                    String hashes = config.getString(propName);
                    if (hashes != null)
                        for (String h : hashes.split(","))
                            storedCerts.add(h);

                    // get the thumbprints from the session allowances
                    List<String> sessionCerts = sessionAllowedCertificates.get(propName);
                    if (sessionCerts != null)
                        storedCerts.addAll(sessionCerts);
                } else {
                    if (serverCheck) {
                        message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT",
                                new String[] { appName, identitiesToTest.toString() });
                    } else {
                        message = R.getI18NString("service.gui." + "CERT_DIALOG_PEER_DESCRIPTION_TXT",
                                new String[] { appName, identitiesToTest.toString() });
                    }
                    for (String identity : identitiesToTest) {
                        String propName = PNAME_CERT_TRUST_PREFIX + ".param." + identity;
                        propNames.add(propName);

                        // get the thumbprints from the permanent allowances
                        String hashes = config.getString(propName);
                        if (hashes != null)
                            for (String h : hashes.split(","))
                                storedCerts.add(h);

                        // get the thumbprints from the session allowances
                        List<String> sessionCerts = sessionAllowedCertificates.get(propName);
                        if (sessionCerts != null)
                            storedCerts.addAll(sessionCerts);
                    }
                }

                if (!storedCerts.contains(thumbprint)) {
                    switch (verify(chain, message)) {
                    case DO_NOT_TRUST:
                        logger.info("Untrusted certificate", e);
                        throw new CertificateException("The peer provided certificate with Subject <"
                                + chain[0].getSubjectDN() + "> is not trusted", e);
                    case TRUST_ALWAYS:
                        for (String propName : propNames) {
                            String current = config.getString(propName);
                            String newValue = thumbprint;
                            if (current != null)
                                newValue += "," + current;
                            config.setProperty(propName, newValue);
                        }
                        break;
                    case TRUST_THIS_SESSION_ONLY:
                        for (String propName : propNames)
                            getSessionCertEntry(propName).add(thumbprint);
                        break;
                    }
                }
                // ok, we've seen this certificate before
            }
        }

        private X509Certificate[] tryBuildChain(X509Certificate[] chain)
                throws IOException, URISyntaxException, CertificateException {
            // Only try to build chains for servers that send only their
            // own cert, but no issuer. This also matches self signed (will
            // be ignored later) and Root-CA signed certs. In this case we
            // throw the Root-CA away after the lookup
            if (chain.length != 1)
                return chain;

            // ignore self signed certs
            if (chain[0].getIssuerDN().equals(chain[0].getSubjectDN()))
                return chain;

            // prepare for the newly created chain
            List<X509Certificate> newChain = new ArrayList<X509Certificate>(chain.length + 4);
            for (X509Certificate cert : chain) {
                newChain.add(cert);
            }

            // search from the topmost certificate upwards
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            X509Certificate current = chain[chain.length - 1];
            boolean foundParent;
            int chainLookupCount = 0;
            do {
                foundParent = false;
                // extract the url(s) where the parent certificate can be
                // found
                byte[] aiaBytes = current.getExtensionValue(Extension.authorityInfoAccess.getId());
                if (aiaBytes == null)
                    break;

                AuthorityInformationAccess aia = AuthorityInformationAccess
                        .getInstance(X509ExtensionUtil.fromExtensionValue(aiaBytes));

                // the AIA may contain different URLs and types, try all
                // of them
                for (AccessDescription ad : aia.getAccessDescriptions()) {
                    // we are only interested in the issuer certificate,
                    // not in OCSP urls the like
                    if (!ad.getAccessMethod().equals(AccessDescription.id_ad_caIssuers))
                        continue;

                    GeneralName gn = ad.getAccessLocation();
                    if (!(gn.getTagNo() == GeneralName.uniformResourceIdentifier
                            && gn.getName() instanceof DERIA5String))
                        continue;

                    URI uri = new URI(((DERIA5String) gn.getName()).getString());
                    // only http(s) urls; LDAP is taken care of in the
                    // default implementation
                    if (!(uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equals("https")))
                        continue;

                    X509Certificate cert = null;

                    // try to get cert from cache first to avoid consecutive
                    // (slow) http lookups
                    AiaCacheEntry cache = aiaCache.get(uri);
                    if (cache != null && cache.cacheDate.after(new Date())) {
                        cert = cache.cert;
                    } else {
                        // download if no cache entry or if it is expired
                        if (logger.isDebugEnabled())
                            logger.debug("Downloading parent certificate for <" + current.getSubjectDN()
                                    + "> from <" + uri + ">");
                        try {
                            InputStream is = HttpUtils.openURLConnection(uri.toString()).getContent();
                            cert = (X509Certificate) certFactory.generateCertificate(is);
                        } catch (Exception e) {
                            logger.debug("Could not download from <" + uri + ">");
                        }
                        // cache for 10mins
                        aiaCache.put(uri,
                                new AiaCacheEntry(new Date(new Date().getTime() + 10 * 60 * 1000), cert));
                    }
                    if (cert != null) {
                        if (!cert.getIssuerDN().equals(cert.getSubjectDN())) {
                            newChain.add(cert);
                            foundParent = true;
                            current = cert;
                            break; // an AD was valid, ignore others
                        } else
                            logger.debug("Parent is self-signed, ignoring");
                    }
                }
                chainLookupCount++;
            } while (foundParent && chainLookupCount < 10);
            chain = newChain.toArray(chain);
            return chain;
        }
    };
}

From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java

private X509Certificate getCertificate(byte[] certData) {
    CertificateFactory certificateFactory;
    try {/*  ww w.j a  v  a  2  s  .c o  m*/
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("cert factory error: " + e.getMessage(), e);
    }
    try {
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(certData));
        return certificate;
    } catch (CertificateException e) {
        throw new RuntimeException("certificate decoding error: " + e.getMessage(), e);
    }
}

From source file:com.mhise.util.MHISEUtil.java

public static File addBeginEndCertificateTag(Context context, File certfile, String filePath) {
    File updatedFile = null;//from   w w  w.  j  a  v a  2s  .co m
    java.security.cert.Certificate[] chain = {};

    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        FileInputStream ins = new FileInputStream(certfile);
        chain = certificateFactory.generateCertificates(ins).toArray(chain);
        ins.close();

        updatedFile = certfile;
    } catch (CertificateException e) {
        // TODO: handle exception
        Logger.debug("MHISEUtil-->addBeginEndCertificateTag", " CertificateException " + e);
        try {
            String TAG_BEGIN_CERTIFICATE = "-----BEGIN CERTIFICATE-----\n";
            String TAG_END_CERTIFICATE = "\n-----END CERTIFICATE-----";

            byte[] kb1 = TAG_BEGIN_CERTIFICATE.getBytes();
            byte[] kb3 = TAG_END_CERTIFICATE.getBytes();

            FileInputStream fis = new FileInputStream(certfile);
            int kl = fis.available();
            byte[] kb2 = new byte[kl];
            fis.read(kb2);
            fis.close();

            certfile.delete();
            updatedFile = new File(filePath);
            FileOutputStream fos = new FileOutputStream(filePath);

            ArrayList<byte[]> list = new ArrayList<byte[]>();
            list.add(kb1);
            list.add(kb2);
            list.add(kb3);
            concatenateByteArrays(list);
            fos.write(concatenateByteArrays(list));
            fos.close();

        } catch (IOException e1) {

            Logger.debug("MHISEUtil-->addBeginEndCertificateTag ", "Inside catch ->try " + e1);
            return null;
        }

        return updatedFile;
    }

    catch (FileNotFoundException e) {
        Logger.debug("MHISEUtil-->addBeginEndCertificateTag ", "FileNotFoundException " + e);
    } catch (IOException e) {
        Logger.debug("MHISEUtil-->addBeginEndCertificateTag ", "IOException " + e);
    }

    return updatedFile;
}

From source file:com.adito.ldap.LdapUserDatabase.java

/**
 * Return the certificat store in LDAP server for a user (if exist)
 * @param user// w  w  w.  j av a  2  s. co  m
 * @return X509Certificate of the user or null id this certificate doesn't exist
 */
public X509Certificate getCertificate(User user) {

    if (logger.isInfoEnabled()) {
        logger.info("Get Certificat for " + user.getPrincipalName());
    }

    LdapTemplate ldapTemplate = new LdapTemplate();
    ldapTemplate.setContextSource(ldapContextSource);

    AndFilter filterS = new AndFilter();
    String dn = ((LdapUser) user).getDn();
    int ind = dn.indexOf(baseDn);
    String rdn = dn.substring(0, ind - 1);
    filterS.and(new EqualsFilter(OBJECT_CLASS_ATTRIBUTE, USERS_CLASS));
    filterS.and(new LikeFilter(UID_ATTRIBUTE, user.getPrincipalName()));
    List certificats = ldapTemplate.search(rdn, filterS.encode(), new AttributesMapper() {
        public Object mapFromAttributes(Attributes attrs) throws NamingException {

            try {
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

                return certificateFactory.generateCertificate(
                        new ByteArrayInputStream((byte[]) attrs.get(CERTIFICATE_ATTRIBUTE).get()));

            } catch (Exception e) {

                throw new NamingException(e.toString());
            }

        }
    });

    if (certificats.size() == 0) {
        return null;
    } else {
        X509Certificate cert = (X509Certificate) certificats.get(0);
        return cert;
    }

}

From source file:com.adito.ldap.LdapUserDatabase.java

/**
 * Return the user associated to a certiciate in LDAP server
 * @param x509Certificate//www .jav a2  s  .co m
 * @return the user of the certificate or null if no associate exist
 */
public User getUserByCertificate(X509Certificate x509Certificate) {

    if (logger.isInfoEnabled()) {
        logger.info("Get user for serial number " + x509Certificate.getSerialNumber().toString(16));
    }

    LdapTemplate ldapTemplate = new LdapTemplate();
    ldapTemplate.setContextSource(ldapContextSource);

    AndFilter filterS = new AndFilter();
    filterS.and(new EqualsFilter(OBJECT_CLASS_ATTRIBUTE, USERS_CLASS));
    filterS.and(new LikeFilter("userCertificate", "*"));
    for (String rdn : rdnUsers) {
        List serialNumbers = ldapTemplate.search(rdn, filterS.encode(), new AbstractContextMapper() {
            public Object doMapFromContext(DirContextOperations ctx) {

                try {
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

                    X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(
                            new ByteArrayInputStream((byte[]) ctx.getObjectAttribute(CERTIFICATE_ATTRIBUTE)));

                    if (ctx.getStringAttribute(MAIL_ATTRIBUTE) == null)
                        ctx.setAttributeValue(MAIL_ATTRIBUTE, "");
                    if (ctx.getStringAttribute(COMMON_NAME_ATTRIBUTE) == null)
                        ctx.setAttributeValue(COMMON_NAME_ATTRIBUTE, "");

                    String uid = ctx.getStringAttribute(UID_ATTRIBUTE);

                    //get the date of last modify of this user
                    LdapTemplate tmp = new LdapTemplate();
                    tmp.setContextSource(ldapContextSource);
                    final String[] attrOp = { MODIFY_TIMESTAMP_ATTRIBUTE };
                    Object o = tmp.lookup(ctx.getDn(), attrOp, new ContextMapper() {
                        public Object mapFromContext(Object ctx) {
                            DirContextAdapter adapter = (DirContextAdapter) ctx;
                            return adapter.getStringAttribute(attrOp[0]);

                        }
                    }

                    );

                    Date lastPasswordChange; //the time of last change for the entry
                    if (o != null) {
                        String modifyTimestamp = o.toString();
                        lastPasswordChange = getDate(modifyTimestamp);
                    } else {
                        //if the modifyTimeStamp is null
                        lastPasswordChange = new Date();
                    }

                    LdapUser user = new LdapUser(uid, ctx.getNameInNamespace(),
                            ctx.getStringAttribute(MAIL_ATTRIBUTE),
                            ctx.getStringAttribute(COMMON_NAME_ATTRIBUTE), lastPasswordChange, getRealm());

                    Object[] tab = { x509Certificate.getSerialNumber(), user };

                    return tab;

                } catch (Exception e) {

                    logger.error(e);
                    return null;
                }
            }
        });

        if (serialNumbers != null) {
            for (Object o : serialNumbers) {

                Object[] tab = (Object[]) o;
                BigInteger serialNumber = (BigInteger) tab[0];
                LdapUser user = (LdapUser) tab[1];
                if (serialNumber.equals(x509Certificate.getSerialNumber()))
                    return user;
            }
        }
    }

    return null;

}

From source file:com.wwpass.connection.WWPassConnection.java

public WWPassConnection(X509Certificate cert, PKCS8EncodedKeySpec key, int timeoutSec, String spfeAddr)
        throws IOException, GeneralSecurityException {
    timeoutMs = timeoutSec * 1000;//from   w  ww.  j  ava2s.c  om
    SpfeURL = "https://" + spfeAddr + "/";
    // Setting up client certificate and key

    X509Certificate[] chain = { cert };

    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey privKey = kf.generatePrivate(key);

    KeyStore.PrivateKeyEntry pke = new KeyStore.PrivateKeyEntry(privKey, chain);

    //This adds no security but Java requires to password-protect the key
    byte[] password_bytes = new byte[16];
    (new java.security.SecureRandom()).nextBytes(password_bytes);
    // String password = (new BASE64Encoder()).encode(password_bytes);
    String password = (new Base64()).encodeToString(password_bytes);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(null);

    keyStore.setEntry("WWPass client key", pke, new KeyStore.PasswordProtection(password.toCharArray()));
    keyManagerFactory.init(keyStore, password.toCharArray());

    SPFEContext = SSLContext.getInstance("TLS");

    // Making rootCA certificate
    InputStream is = null;
    CertificateFactory cf;
    X509Certificate rootCA = null;
    try {
        is = new ByteArrayInputStream(WWPassCA_DER);
        cf = CertificateFactory.getInstance("X.509");
        rootCA = (X509Certificate) cf.generateCertificate(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }

    //Creating TrustManager for this CA
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);
    ks.setCertificateEntry("WWPass Root CA", rootCA);

    trustManagerFactory.init(ks);

    SPFEContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new java.security.SecureRandom());
}