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:com.wwpass.connection.WWPassConnection.java

public WWPassConnection(X509Certificate cert, PKCS8EncodedKeySpec key, int timeoutSec, String spfeAddr)
        throws IOException, GeneralSecurityException {
    timeoutMs = timeoutSec * 1000;/*from w w  w. j av  a 2 s .  c  o m*/
    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());
}

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

public X509Certificate getCertFromString(String certificateHeader) {
    CertificateFactory certificateFactory;
    try {/*  w  w  w.j  a  v a2s.c  om*/
        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.");
    }/*from   w w  w.  j a v 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:org.ejbca.util.CertTools.java

/**
 * Creates Certificate from byte[], can be either an X509 certificate or a CVCCertificate
 *
 * @param cert byte array containing certificate in binary (DER) format, or PEM encoded X.509 certificate
 * @param provider provider for example "SUN" or "BC", use null for the default provider (BC)
 *
 * @return Certificate//  w w  w.ja v  a2  s  .co m
 *
 * @throws CertificateException if the byte array does not contain a proper certificate.
 * @throws IOException if the byte array cannot be read.
 */
public static Certificate getCertfromByteArray(byte[] cert, String provider) throws CertificateException {
    /*if (log.isTraceEnabled()) {
       log.trace(">getCertfromByteArray");
    }*/
    Certificate ret = null;
    String prov = provider;
    if (provider == null) {
        prov = "BC";
    }
    try {
        CertificateFactory cf = CertTools.getCertificateFactory(prov);
        ret = cf.generateCertificate(new ByteArrayInputStream(cert));
    } catch (CertificateException e) {
        log.debug("CertificateException trying to read X509Certificate.");
    }
    if (ret == null) {
        // We could not create an X509Certificate, see if it is a CVC certificate instead
        try {
            CVCertificate parsedObject = CertificateParser.parseCertificate(cert);
            ret = new CardVerifiableCertificate(parsedObject);
        } catch (ParseException e) {
            log.debug("ParseException trying to read CVCCertificate.");
            throw new CertificateException("Certificate exception trying to read CVCCertificate", e);
        } catch (ConstructionException e) {
            log.debug("ConstructionException trying to read CVCCertificate.");
            throw new CertificateException("Certificate exception trying to read CVCCertificate", e);
        } catch (IllegalArgumentException e) {
            log.debug("CertificateException trying to read CVCCertificate.");
            throw new CertificateException("Certificate exception trying to read CVCCertificate", e);
        }
    }
    if (ret == null) {
        throw new CertificateException("No certificate found");
    }
    //log.trace("<getCertfromByteArray");
    return ret;
}

From source file:org.ejbca.util.CertTools.java

/**
 * Gets subject or issuer DN in the format we are sure about (BouncyCastle),supporting UTF8.
 *
 * @param cert X509Certificate//from   ww  w  . j a va 2s.c  om
 * @param which 1 = subjectDN, anything else = issuerDN
 *
 * @return String containing the DN.
 */
private static String getDN(Certificate cert, int which) {
    /*if (log.isTraceEnabled()) {
       log.trace(">getDN("+which+")");
    }*/
    String ret = null;
    if (cert == null) {
        return null;
    }
    if (cert instanceof X509Certificate) {
        // cert.getType=X.509
        try {
            CertificateFactory cf = CertTools.getCertificateFactory();
            X509Certificate x509cert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cert.getEncoded()));
            //log.debug("Created certificate of class: " + x509cert.getClass().getName());
            String dn = null;
            if (which == 1) {
                dn = x509cert.getSubjectDN().toString();
            } else {
                dn = x509cert.getIssuerDN().toString();
            }
            ret = stringToBCDNString(dn);
        } catch (CertificateException ce) {
            log.info("Could not get DN from X509Certificate. " + ce.getMessage());
            log.debug("", ce);
            return null;
        }
    } else if (StringUtils.equals(cert.getType(), "CVC")) {
        CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert;
        try {
            ReferenceField rf = null;
            if (which == 1) {
                rf = cvccert.getCVCertificate().getCertificateBody().getHolderReference();
            } else {
                rf = cvccert.getCVCertificate().getCertificateBody().getAuthorityReference();
            }
            if (rf != null) {
                // Construct a "fake" DN which can be used in EJBCA
                // Use only mnemonic and country, since sequence is more of a serialnumber than a DN part
                String dn = "";
                //                if (rf.getSequence() != null) {
                //                   dn += "SERIALNUMBER="+rf.getSequence();
                //                }
                if (rf.getMnemonic() != null) {
                    if (StringUtils.isNotEmpty(dn)) {
                        dn += ", ";
                    }
                    dn += "CN=" + rf.getMnemonic();
                }
                if (rf.getCountry() != null) {
                    if (StringUtils.isNotEmpty(dn)) {
                        dn += ", ";
                    }
                    dn += "C=" + rf.getCountry();
                }
                ret = stringToBCDNString(dn);
            }
        } catch (NoSuchFieldException e) {
            log.error("NoSuchFieldException: ", e);
            return null;
        }
    }
    /*if (log.isTraceEnabled()) {
       log.trace("<getDN("+which+"):"+dn);
    }*/
    return ret;
}

From source file:com.cloud.bridge.service.EC2RestServlet.java

/**
 * The SOAP API for EC2 uses WS-Security to sign all client requests.  This requires that 
 * the client have a public/private key pair and the public key defined by a X509 certificate.
 * Thus in order for a Cloud.com account holder to use the EC2's SOAP API he must register
 * his X509 certificate with the EC2 service.   This function allows the Cloud.com account
 * holder to "load" his X509 certificate into the service.   Note, that the SetUserKeys REST
 * function must be called before this call.
 * /*from   w ww .ja va 2s.c  om*/
 * This is an authenticated REST call and as such must contain all the required REST parameters
 * including: Signature, Timestamp, Expires, etc.   The signature is calculated using the
 * Cloud.com account holder's API access and secret keys and the Amazon defined EC2 signature
 * algorithm.
 * 
 * A user can call this REST function any number of times, on each call the X509 certificate
 * simply over writes any previously stored value.
 */
private void setCertificate(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Transaction txn = null;
    try {
        // [A] Pull the cert and cloud AccessKey from the request
        String[] certificate = request.getParameterValues("cert");
        if (null == certificate || 0 == certificate.length) {
            response.sendError(530, "Missing cert parameter");
            return;
        }
        //           logger.debug( "SetCertificate cert: [" + certificate[0] + "]" );

        String[] accessKey = request.getParameterValues("AWSAccessKeyId");
        if (null == accessKey || 0 == accessKey.length) {
            response.sendError(530, "Missing AWSAccessKeyId parameter");
            return;
        }

        // [B] Open our keystore
        FileInputStream fsIn = new FileInputStream(pathToKeystore);
        KeyStore certStore = KeyStore.getInstance("JKS");
        certStore.load(fsIn, keystorePassword.toCharArray());

        // -> use the Cloud API key to save the cert in the keystore
        // -> write the cert into the keystore on disk
        Certificate userCert = null;
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        ByteArrayInputStream bs = new ByteArrayInputStream(certificate[0].getBytes());
        while (bs.available() > 0)
            userCert = cf.generateCertificate(bs);
        certStore.setCertificateEntry(accessKey[0], userCert);

        FileOutputStream fsOut = new FileOutputStream(pathToKeystore);
        certStore.store(fsOut, keystorePassword.toCharArray());

        // [C] Associate the cert's uniqueId with the Cloud API keys
        String uniqueId = AuthenticationUtils.X509CertUniqueId(userCert);
        logger.debug("SetCertificate, uniqueId: " + uniqueId);
        /*           UserCredentialsDao credentialDao = new UserCredentialsDao();
                   credentialDao.setCertificateId( accessKey[0], uniqueId );
        */
        txn = Transaction.open(Transaction.AWSAPI_DB);
        UserCredentialsVO user = ucDao.getByAccessKey(accessKey[0]);
        user.setCertUniqueId(uniqueId);
        ucDao.update(user.getId(), user);
        response.setStatus(200);
        endResponse(response, "User certificate set successfully");
        txn.commit();

    } catch (NoSuchObjectException e) {
        logger.error("SetCertificate exception " + e.getMessage(), e);
        response.sendError(404, "SetCertificate exception " + e.getMessage());

    } catch (Exception e) {
        logger.error("SetCertificate exception " + e.getMessage(), e);
        response.sendError(500, "SetCertificate exception " + e.getMessage());
    } finally {
        txn.close();
    }

}

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java

/**
 * Generate a socket factory using supplied key and trust stores 
 *///w w  w.jav  a  2 s. c  o  m
protected SSLConnectionSocketFactory getSocketFactory() throws IOException {
    TrustManager[] trustManagers = null;
    KeyManager[] keyManagers = null;

    try {
        /* trust managers */
        if (caCertificateFile != null) {
            KeyStore trustStore;
            int cn = 0;

            log.info("Setting x509 trust from " + caCertificateFile);

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            FileInputStream in = new FileInputStream(caCertificateFile);
            Collection certs = cf.generateCertificates(in);

            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            Iterator cit = certs.iterator();
            while (cit.hasNext()) {
                X509Certificate cert = (X509Certificate) cit.next();
                log.info(" adding " + cert.getSubjectX500Principal().toString());
                System.out.println(" adding " + cert.getSubjectX500Principal().toString());
                trustStore.setCertificateEntry("CACERT" + cn, cert);
                cn += 1;
            }
            tmf.init(trustStore);
            trustManagers = tmf.getTrustManagers();
        } else { // no verification
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    return;
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    return;
                }
            } };
        }

        /* key manager */
        if (certificateFile != null && keyFile != null) {
            KeyStore keyStore;
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);

            FileInputStream in = new FileInputStream(certificateFile);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
            PKCS1 pkcs = new PKCS1();
            log.info("reading key file: " + keyFile);
            PrivateKey key = pkcs.readKey(keyFile);

            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            keyStore.setKeyEntry("CERT", (Key) key, "pw".toCharArray(), chain);
            kmf.init(keyStore, "pw".toCharArray());
            keyManagers = kmf.getKeyManagers();
        }

        /* socket factory */

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagers, null);
        return new SSLConnectionSocketFactory(ctx);

    } catch (IOException e) {
        log.error("error reading cert or key error: " + e);
    } catch (KeyStoreException e) {
        log.error("keystore error: " + e);
    } catch (NoSuchAlgorithmException e) {
        log.error("sf error: " + e);
    } catch (KeyManagementException e) {
        log.error("sf error: " + e);
    } catch (CertificateException e) {
        log.error("sf error: " + e);
    } catch (UnrecoverableKeyException e) {
        log.error("sf error: " + e);
    }

    return null;

}

From source file:eu.eidas.auth.engine.EIDASSAMLEngine.java

/**
 * Gets the country from X.509 Certificate.
 * /*  www  .j a  va 2  s . com*/
 * @param keyInfo the key info
 * 
 * @return the country
 */
private String getCountry(final KeyInfo keyInfo) {
    LOG.trace("Recover country information.");

    String result = "";
    try {
        final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0)
                .getX509Certificates().get(0);

        // Transform the KeyInfo to X509Certificate.
        CertificateFactory certFact;
        certFact = CertificateFactory.getInstance("X.509");

        final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));

        final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);

        String distName = cert.getSubjectDN().toString();

        distName = StringUtils.deleteWhitespace(StringUtils.upperCase(distName));

        final String countryCode = "C=";
        final int init = distName.indexOf(countryCode);

        if (init > StringUtils.INDEX_NOT_FOUND) {
            // Exist country code.
            int end = distName.indexOf(',', init);

            if (end <= StringUtils.INDEX_NOT_FOUND) {
                end = distName.length();
            }

            if (init < end && end > StringUtils.INDEX_NOT_FOUND) {
                result = distName.substring(init + countryCode.length(), end);
                //It must be a two characters value
                if (result.length() > 2) {
                    result = result.substring(0, 2);
                }
            }
        }

    } catch (CertificateException e) {
        LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getCountry from certificate. {}", e.getMessage());
        LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getCountry from certificate. {}", e);
    }
    return result.trim();
}

From source file:eu.eidas.auth.engine.EIDASSAMLEngine.java

/**
 * Gets the alias from X.509 Certificate at keystore.
 * // w ww  .  j a  v  a 2s  . c o m
 * @param keyInfo the key info
 * @param ownKeyStore 
 * @param ownKeyStore 
 * 
 * @return the alias
 */
private String getAlias(final KeyInfo keyInfo, KeyStore ownKeyStore) {

    LOG.trace("Recover alias information");

    String alias = null;
    try {
        final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0)
                .getX509Certificates().get(0);

        // Transform the KeyInfo to X509Certificate.
        CertificateFactory certFact;
        certFact = CertificateFactory.getInstance("X.509");

        final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));

        final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);

        final String tokenSerialNumber = cert.getSerialNumber().toString(HEXA);
        final X500Name tokenIssuerDN = new X500Name(cert.getIssuerDN().getName());

        String aliasCert;
        X509Certificate certificate;
        boolean find = false;

        for (final Enumeration<String> e = ownKeyStore.aliases(); e.hasMoreElements() && !find;) {
            aliasCert = e.nextElement();
            certificate = (X509Certificate) ownKeyStore.getCertificate(aliasCert);

            final String serialNum = certificate.getSerialNumber().toString(HEXA);

            X500Name issuerDN = new X500Name(certificate.getIssuerDN().getName());

            if (serialNum.equalsIgnoreCase(tokenSerialNumber)
                    && X500PrincipalUtil.principalEquals(issuerDN, tokenIssuerDN)) {
                alias = aliasCert;
                find = true;
            }

        }

    } catch (KeyStoreException e) {
        LOG.info(SAML_EXCHANGE,
                "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}",
                e.getMessage());
        LOG.debug(SAML_EXCHANGE,
                "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}",
                e);
    } catch (CertificateException e) {
        LOG.info(SAML_EXCHANGE,
                "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}",
                e.getMessage());
        LOG.debug(SAML_EXCHANGE,
                "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}",
                e);
    } catch (RuntimeException e) {
        LOG.info(SAML_EXCHANGE,
                "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}",
                e.getMessage());
        LOG.debug(SAML_EXCHANGE,
                "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}",
                e);
    }
    return alias;
}