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:org.jvnet.hudson.update_center.Signing.java

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

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

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

From source file:be.fedict.eidviewer.lib.file.imports.Version35XMLFile.java

public void load(File file) throws CertificateException, FileNotFoundException, SAXException, IOException,
        ParseException, DataConvertorException {
    logger.fine("Loading Version 35X XML File");

    XMLReader reader = null;//from   w w  w.ja  v a 2s . c o  m

    certificateFactory = CertificateFactory.getInstance("X.509");
    DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
    FileInputStream fis = new FileInputStream(file);

    reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(this);
    reader.setErrorHandler(this);
    BufferedReader in = new BufferedReader(new InputStreamReader(fis));
    reader.parse(new InputSource(in));

    Identity identity = new Identity();
    identity.cardDeliveryMunicipality = discreteValues.get("issuing_municipality");
    identity.cardNumber = discreteValues.get("logical_nr");
    GregorianCalendar validityStartCalendar = new GregorianCalendar();
    validityStartCalendar.setTime(dateFormat.parse(discreteValues.get("date_begin")));
    identity.cardValidityDateBegin = validityStartCalendar;
    GregorianCalendar validityEndCalendar = new GregorianCalendar();
    validityEndCalendar.setTime(dateFormat.parse(discreteValues.get("date_end")));
    identity.cardValidityDateEnd = validityEndCalendar;
    identity.chipNumber = discreteValues.get("chip_nr");
    identity.dateOfBirth = (new DateOfBirthDataConvertor())
            .convert(discreteValues.get("date_of_birth").getBytes());
    identity.documentType = DocumentType.toDocumentType(discreteValues.get("type").getBytes());
    identity.duplicate = discreteValues.get("duplicata");
    identity.gender = discreteValues.get("gender").equals("M") ? Gender.MALE : Gender.FEMALE;

    TextFormatHelper.setFirstNamesFromString(identity, discreteValues.get("name"));
    identity.name = discreteValues.get("surname");

    identity.nationalNumber = discreteValues.get("national_nr");
    identity.nationality = discreteValues.get("nationality");
    identity.nobleCondition = discreteValues.get("nobility");
    identity.placeOfBirth = discreteValues.get("location_of_birth");
    identity.specialStatus = SpecialStatus.toSpecialStatus(discreteValues.get("specialStatus"));
    eidData.setIdentity(identity);

    Address address = new Address();
    address.municipality = discreteValues.get("municipality");
    address.zip = discreteValues.get("zip");
    address.streetAndNumber = discreteValues.get("street");
    eidData.setAddress(address);

    eidData.setPhoto(pictureData);

    X509Utilities.setCertificateChainsFromCertificates(eidData, rootCert, citizenCert, authenticationCert,
            signingCert, rrnCert);
}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

public DigSigUtil() throws CertificateException {
    cf = CertificateFactory.getInstance("X.509");
}

From source file:com.vmware.identity.sts.auth.impl.UserCertAuthenticator.java

@Override
public Result authenticate(Request req) throws AuthenticationFailedException, UnsupportedSecurityTokenException,
        NoSuchIdPException, RequestFailedException {
    assert req != null && req.getHeader() != null;
    log.trace("Authenticating by User Cert...");

    UserCertificateTokenType userCertToken = JAXBExtractor.extractFromSecurityHeader(req.getHeader(),
            UserCertificateTokenType.class);
    if (userCertToken == null) {
        log.debug("No UserCertificateToken found!");
        return null;
    }//from  ww w . j  a va  2s .c o  m

    SignatureAlgorithmType signatureAlgorithm = userCertToken.getSignatureAlgorithm();
    BinarySecurityTokenType binarySecurityToken = userCertToken.getUserCertificate();
    String signedInfo = userCertToken.getSignatureInfo();
    SignatureValueType signatureValueType = userCertToken.getSignatureValue();
    if (signatureAlgorithm == null || binarySecurityToken == null || signedInfo == null
            || signatureValueType == null) {
        throw new InvalidCredentialsException(
                "User certificate token does not include all required information!");
    }

    if (signatureAlgorithm != SignatureAlgorithmType.SHA_256_WITH_RSA) {
        log.debug(String.format(
                "UserCertificateToken should use %s algorithm, but %s found. "
                        + "No authentication will be done",
                SignatureAlgorithmType.SHA_256_WITH_RSA.value(), signatureAlgorithm.value()));
        throw new InvalidCredentialsException(
                "User certificate token signature algorithm should be SHA256RSA!");
    }

    String userCertificate = binarySecurityToken.getValue();

    byte[] decoded = new Base64().decode(userCertificate);
    X509Certificate x509Certificate = null;
    try {
        x509Certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(new ByteArrayInputStream(decoded));
    } catch (CertificateException e) {
        throw new InvalidCredentialsException("User certificate is not valid in User certificate token");
    }

    byte[] signatureValue = signatureValueType.getValue();
    if (signatureValue == null) {
        throw new InvalidCredentialsException("Signature value is required in User certificate token!");
    }

    if (!verifyUserCertSignature(x509Certificate, signedInfo, signatureValue)) {
        throw new InvalidCredentialsException("User certificate token signature validation failed.");
    }

    PrincipalId authenticatedPrincipal = this.idmAuthenticator
            .authenticate(new X509Certificate[] { x509Certificate });

    final Date authenticationTime = new Date();
    log.debug("Authenticated principal: {} by user certificate at time: {}", authenticatedPrincipal,
            authenticationTime);

    return new Result(authenticatedPrincipal, authenticationTime, Result.AuthnMethod.SMARTCARD);
}

From source file:com.cloudbees.tftwoway.Client.java

private static X509Certificate loadX509Key(String path) throws Exception {
    try (FileInputStream fis = new FileInputStream(path)) {
        return (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(new BufferedInputStream(fis));
    }//www  .  j  av  a  2 s. com
}

From source file:eu.europa.ec.markt.dss.validation.crl.JdbcCacheCRLSource.java

@Override
public X509CRL findCrl(X509Certificate certificate, X509Certificate issuerCertificate) throws IOException {

    OnlineCRLSource source = new OnlineCRLSource();
    String crlUrl = source.getCrlUri(certificate);

    if (crlUrl != null) {
        try {//from   w  ww  .j  av a  2  s  .  co  m
            MessageDigest digest = MessageDigest.getInstance(DigestAlgorithm.SHA1.getName());
            String key = Hex.encodeHexString(digest.digest(crlUrl.getBytes()));

            List<CachedCRL> crls = getJdbcTemplate().query("SELECT * FROM CACHED_CRL WHERE ID = ?",
                    new Object[] { key }, new RowMapper<CachedCRL>() {
                        @Override
                        public CachedCRL mapRow(ResultSet rs, int rowNum) throws SQLException {
                            CachedCRL cached = new CachedCRL();
                            cached.setKey(rs.getString("ID"));
                            cached.setCrl(rs.getBytes("DATA"));
                            return cached;
                        }
                    });

            if (crls.size() == 0) {
                LOG.info("CRL not in cache");
                X509CRL originalCRL = cachedSource.findCrl(certificate, issuerCertificate);
                if (originalCRL != null) {
                    getJdbcTemplate().update("INSERT INTO CACHED_CRL (ID, DATA) VALUES (?,?) ", key,
                            originalCRL.getEncoded());
                    return originalCRL;
                } else {
                    return null;
                }
            }

            CachedCRL crl = crls.get(0);

            CertificateFactory factory = CertificateFactory.getInstance("X509");
            X509CRL x509crl = (X509CRL) factory.generateCRL(new ByteArrayInputStream(crl.getCrl()));
            if (x509crl.getNextUpdate().after(new Date())) {
                LOG.fine("CRL in cache");
                return x509crl;
            } else {
                LOG.info("CRL expired");
                X509CRL originalCRL = cachedSource.findCrl(certificate, issuerCertificate);
                getJdbcTemplate().update("UPDATE CACHED_CRL SET DATA = ?  WHERE ID = ? ",
                        originalCRL.getEncoded(), key);
                return originalCRL;
            }

        } catch (NoSuchAlgorithmException e) {
            LOG.info("Cannot instantiate digest for algorithm SHA1 !?");
        } catch (CRLException e) {
            LOG.info("Cannot serialize CRL");
        } catch (CertificateException e) {
            LOG.info("Cannot instanciate X509 Factory");
        }
    }

    return null;
}

From source file:org.apache.tomcat.util.net.jsse.JSSESupport.java

protected java.security.cert.X509Certificate[] getX509Certificates(SSLSession session) throws IOException {
    X509Certificate jsseCerts[] = null;
    try {//from w ww.  j  a  va  2 s .c o  m
        jsseCerts = session.getPeerCertificateChain();
    } catch (Throwable ex) {
        // Get rid of the warning in the logs when no Client-Cert is
        // available
    }

    if (jsseCerts == null)
        jsseCerts = new X509Certificate[0];
    java.security.cert.X509Certificate[] x509Certs = new java.security.cert.X509Certificate[jsseCerts.length];
    for (int i = 0; i < x509Certs.length; i++) {
        try {
            byte buffer[] = jsseCerts[i].getEncoded();
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
            x509Certs[i] = (java.security.cert.X509Certificate) cf.generateCertificate(stream);
            if (log.isTraceEnabled())
                log.trace("Cert #" + i + " = " + x509Certs[i]);
        } catch (Exception ex) {
            log.info("Error translating " + jsseCerts[i], ex);
            return null;
        }
    }

    if (x509Certs.length < 1)
        return null;
    return x509Certs;
}

From source file:net.unicon.cas.support.wsfederation.WsFederationUtils.java

/**
 * getSigningCredential loads up an X509Credential from a file.
 *
 * @param resource the signing certificate file
 * @return an X509 credential//from  w  ww .j  a  va 2 s  . c  o m
 */
public static X509Credential getSigningCredential(final Resource resource) {
    try (final InputStream inputStream = resource.getInputStream()) {
        //grab the certificate file
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        final X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(inputStream);

        //get the public key from the certificate
        final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
                certificate.getPublicKey().getEncoded());

        //generate public key to validate signatures
        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        final PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        //add the public key
        final BasicX509Credential publicCredential = new BasicX509Credential();
        publicCredential.setPublicKey(publicKey);
        LOGGER.debug("getSigningCredential: key retrieved.");
        return publicCredential;
    } catch (final Exception ex) {
        LOGGER.error("I/O error retrieving the signing cert: {}", ex);
        return null;
    }
}

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;//from w w w . j  av a  2 s .c om
    try {
        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:org.apache.tomcat.util.net.puretls.PureTLSSupport.java

public Object[] getPeerCertificateChain(boolean force) throws IOException {
    Vector v = ssl.getCertificateChain();

    if (v == null && force) {
        SSLPolicyInt policy = new SSLPolicyInt();
        policy.requireClientAuth(true);/* ww  w .j a va2  s. c om*/
        policy.handshakeOnConnect(false);
        policy.waitOnClose(false);
        ssl.renegotiate(policy);
        v = ssl.getCertificateChain();
    }

    if (v == null)
        return null;

    java.security.cert.X509Certificate[] chain = new java.security.cert.X509Certificate[v.size()];

    try {
        for (int i = 1; i <= v.size(); i++) {
            // PureTLS provides cert chains with the peer
            // cert last but the Servlet 2.3 spec (S 4.7) requires
            // the opposite order so we reverse the chain as we go
            byte buffer[] = ((X509Cert) v.elementAt(v.size() - i)).getDER();

            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            ByteArrayInputStream stream = new ByteArrayInputStream(buffer);

            X509Certificate xCert = (X509Certificate) cf.generateCertificate(stream);
            chain[i - 1] = xCert;
            if (logger.isTraceEnabled()) {
                logger.trace("Cert # " + i + " = " + xCert);
            }
        }
    } catch (java.security.cert.CertificateException e) {
        logger.info("JDK's broken cert handling can't parse this certificate (which PureTLS likes)", e);
        throw new IOException("JDK's broken cert handling can't parse this certificate (which PureTLS likes)");
    }
    return chain;
}