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:be.fedict.eidviewer.lib.file.imports.Version35CSVFile.java

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

    String line = null;/*from   ww  w.j  a va  2s.com*/

    certificateFactory = CertificateFactory.getInstance("X.509");
    InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "utf-8");
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    line = bufferedReader.readLine();
    if (line != null) {
        String[] tokens = line.split(";");
        for (int tokenNumber = 0; (variableCertCount < 0) && (tokenNumber < tokens.length); tokenNumber++) {
            String token = tokens[tokenNumber];
            logger.log(Level.FINEST, "token #{0} : [{1}]", new Object[] { tokenNumber, token });

            try {

                switch (tokenNumber) {
                case DOCUMENTTYPE:
                    identity = new Identity();
                    identity.documentType = DocumentType.toDocumentType(token.getBytes("utf-8"));
                    if (identity.documentType == null)
                        logger.log(Level.SEVERE, "Unknown Document Type \"{0}\"", token);
                    break;

                case FIRSTNAMES:
                    TextFormatHelper.setFirstNamesFromString(identity, token);
                    break;

                case LASTNAME:
                    identity.name = token;
                    break;

                case GENDER:
                    identity.gender = token.equals("M") ? Gender.MALE : Gender.FEMALE;
                    break;

                case BIRTHDATE: {
                    logger.fine("field BIRTHDATE");
                    DateOfBirthDataConvertor dateOfBirthConvertor = new DateOfBirthDataConvertor();
                    identity.dateOfBirth = dateOfBirthConvertor.convert(token.getBytes("utf-8"));
                }
                    break;

                case PLACEOFBIRTH:
                    identity.placeOfBirth = token;
                    break;

                case NATIONALITY:
                    identity.nationality = token;
                    break;

                case NATIONALNUMBER:
                    identity.nationalNumber = token;
                    break;

                case CARDNUMBER:
                    identity.cardNumber = token;
                    break;

                case CARDCHIPNUMBER:
                    identity.chipNumber = token;
                    break;

                case CARDVALIDFROM: {
                    GregorianCalendar validityBeginCalendar = new GregorianCalendar();
                    try {
                        validityBeginCalendar.setTime(dateFormat.parse(token));
                        identity.cardValidityDateBegin = validityBeginCalendar;
                    } catch (ParseException ex) {
                        logger.log(Level.SEVERE, "Failed to parse Card Validity Start Date \"" + token + "\"",
                                ex);
                    }
                }
                    break;

                case CARDVALIDUNTIL:
                    GregorianCalendar validityEndCalendar = new GregorianCalendar();
                    try {
                        validityEndCalendar.setTime(dateFormat.parse(token));
                        identity.cardValidityDateEnd = validityEndCalendar;
                    } catch (ParseException ex) {
                        logger.log(Level.SEVERE, "Failed to parse Card Validity End Date \"" + token + "\"",
                                ex);
                    }
                    break;

                case CARDISSUINGMUNICIPALITY:
                    identity.cardDeliveryMunicipality = token;
                    break;

                case STREETANDNUMBER:
                    address = new Address();
                    address.streetAndNumber = token;
                    break;

                case ZIP:
                    address.zip = token;
                    break;

                case MUNICIPALITY:
                    address.municipality = token;
                    break;

                case PHOTO:
                    byte[] tokenBytes = token.getBytes();
                    eidData.setPhoto(Base64.decodeBase64(tokenBytes));
                    break;

                case RRNCERTIFICATE:
                    logger.finer("Gathering RRN Certificate");
                    try {
                        rrnCert = (X509Certificate) certificateFactory.generateCertificate(
                                new ByteArrayInputStream(Base64.decodeBase64(token.getBytes())));
                    } catch (CertificateException ex) {
                        logger.log(Level.SEVERE, "Failed to RRN Certificate", ex);
                    }
                    break;

                case CERTCOUNT:
                    logger.finer("Certificate Count: [" + token + "]");
                    variableCertCount = Integer.parseInt(token);
                    break;
                }
            } catch (UnsupportedEncodingException ex) {
                logger.log(Level.SEVERE, "Unsupported Encoding for Token " + tokenNumber, ex);
            } catch (DataConvertorException ex) {
                logger.log(Level.SEVERE,
                        "Couldn't Convert Date \"" + tokens[tokenNumber] + "\" in Token " + tokenNumber, ex);
            }
        } // done looping over fixed parts..

        if (identity != null) {
            TextFormatHelper.setFirstNamesFromStrings(identity, identity.getFirstName(),
                    identity.getMiddleName());
            eidData.setIdentity(identity);
        }

        if (address != null)
            eidData.setAddress(address);

        // get variableCertCount variable certs
        for (int i = 0; i < variableCertCount; i++) {
            X509Certificate thisCertificate = null;
            int certOffset = CERTBASE + (CERTFIELDS * i);
            String certType = tokens[certOffset + CERT_NAME_OFFSET];
            String certData = tokens[certOffset + CERT_DATA_OFFSET];

            logger.finer("Gathering " + certType + " Certificate");

            try {
                thisCertificate = (X509Certificate) certificateFactory.generateCertificate(
                        new ByteArrayInputStream(Base64.decodeBase64(certData.getBytes())));
            } catch (CertificateException ex) {
                logger.log(Level.SEVERE, "Failed to Convert Signing Certificate", ex);
                thisCertificate = null;
            }

            if (thisCertificate != null) {
                if (certType.equalsIgnoreCase("Authentication"))
                    authenticationCert = thisCertificate;
                else if (certType.equalsIgnoreCase("Signature"))
                    signingCert = thisCertificate;
                else if (certType.equalsIgnoreCase("CA"))
                    citizenCert = thisCertificate;
                else if (certType.equalsIgnoreCase("Root"))
                    rootCert = thisCertificate;
            }
        }

    }

    if (rootCert != null && citizenCert != null) {
        logger.fine("Certificates were gathered");

        if (rrnCert != null) {
            logger.fine("Setting RRN Certificate Chain");
            List<X509Certificate> rrnChain = new LinkedList<X509Certificate>();
            rrnChain.add(rrnCert);
            rrnChain.add(rootCert);
            eidData.setRRNCertChain(new X509CertificateChainAndTrust(
                    TrustServiceDomains.BELGIAN_EID_NATIONAL_REGISTRY_TRUST_DOMAIN, rrnChain));
        }

        if (authenticationCert != null) {
            logger.fine("Setting Authentication Certificate Chain");
            List<X509Certificate> authChain = new LinkedList<X509Certificate>();
            authChain.add(authenticationCert);
            authChain.add(citizenCert);
            authChain.add(rootCert);
            eidData.setAuthCertChain(new X509CertificateChainAndTrust(
                    TrustServiceDomains.BELGIAN_EID_AUTH_TRUST_DOMAIN, authChain));
        }

        if (signingCert != null) {
            logger.fine("Setting Signing Certificate Chain");
            List<X509Certificate> signChain = new LinkedList<X509Certificate>();
            signChain.add(signingCert);
            signChain.add(citizenCert);
            signChain.add(rootCert);
            eidData.setSignCertChain(new X509CertificateChainAndTrust(
                    TrustServiceDomains.BELGIAN_EID_NON_REPUDIATION_TRUST_DOMAIN, signChain));
        }
    }
    inputStreamReader.close();
}

From source file:org.josso.auth.scheme.validation.AbstractX509CertificateValidator.java

/**
 * Generates certificate path from supplied client certificate
 * and CA certificates./*from  w  w  w .ja va 2 s.  c o  m*/
 * 
 * @param clientCertificate client certificate
 * @return certificate path
 * @throws CertificateException
 */
protected CertPath generateCertificatePath(X509Certificate clientCertificate) throws CertificateException {
    if (!_initialized) {
        initialize();
    }
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(clientCertificate);
    certs.addAll(_caCerts);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    return cf.generateCertPath(certs);
}

From source file:com.vmware.eucenablement.saml.impl.SAMLUtil.java

/**
 * transfer certificate content to X509Certificate object
 *
 * @param cert/*from w  w  w . j a v a2  s.  com*/
 *            content of certificate
 * @return X509Certificate object
 */
public static X509Certificate transfer2X509Certificate(String cert) {

    // return null if no certificate content
    if (null == cert) {
        log.error("The input cert for transfer2X509Certificate is null!");
        return null;
    }
    /*
     * Test cert = "-----BEGIN CERTIFICATE-----\n" +
     * "MIID7DCCAtSgAwIBAgIFFHYYEzIwDQYJKoZIhvcNAQELBQAwgawxCzAJBgNVBAYT\n"
     * "qNHgsx8lHUoenasijd4sJPnj3YKz2Q9lHjSIOgMK41PSgVymOY2W7y2ANoNNKR0Q\n"
     * + "-----END CERTIFICATE-----";
     */
    if (!cert.contains(VidmSamlConstants.BEGIN_CERT)) {
        cert = convertCertToPemFormat(cert);
    }

    InputStream certinputstream = new ByteArrayInputStream(cert.getBytes());
    CertificateFactory cf = null;
    X509Certificate x509 = null;
    try {
        cf = CertificateFactory.getInstance("X.509");
        x509 = (X509Certificate) cf.generateCertificate(certinputstream);
    } catch (CertificateException e) {
        log.error("Caught CertificateException", e);
        return null;
    }

    return x509;
}

From source file:com.aware.ui.Plugins_Manager.java

/**
* Downloads and compresses image for optimized icon caching
* @param image_url/*  w  w  w . j  a v a 2  s.c  om*/
* @return
*/
public static byte[] cacheImage(String image_url, Context sContext) {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = sContext.getResources().openRawResource(R.raw.aware);
        Certificate ca;
        try {
            ca = cf.generateCertificate(caInput);
        } finally {
            caInput.close();
        }

        KeyStore sKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream inStream = sContext.getResources().openRawResource(R.raw.awareframework);
        sKeyStore.load(inStream, "awareframework".toCharArray());
        inStream.close();

        sKeyStore.setCertificateEntry("ca", ca);

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(sKeyStore);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        //Fetch image now that we recognise SSL
        URL image_path = new URL(image_url.replace("http://", "https://")); //make sure we are fetching the images over https
        HttpsURLConnection image_connection = (HttpsURLConnection) image_path.openConnection();
        image_connection.setSSLSocketFactory(context.getSocketFactory());

        InputStream in_stream = image_connection.getInputStream();
        Bitmap tmpBitmap = BitmapFactory.decodeStream(in_stream);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        tmpBitmap.compress(Bitmap.CompressFormat.PNG, 100, output);

        return output.toByteArray();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.vmware.identity.samlservice.impl.AuthnRequestStateTLSClientAuthenticationFilter.java

@Override
public void authenticate(AuthnRequestState t) throws SamlServiceException {
    log.debug("AuthnRequestStateTLSClientAuthenticationFilter.authenticate is called");

    Validate.notNull(t);// w ww .ja  va2  s  .  c om
    IdmAccessor accessor = t.getIdmAccessor();
    Validate.notNull(accessor);
    HttpServletRequest request = t.getRequest();
    Validate.notNull(request);
    AuthnRequest authnRequest = t.getAuthnRequest();
    Validate.notNull(authnRequest);

    PrincipalId principalId = null;

    X509Certificate certChain[] = null;

    //Get from the custom header first.
    String certStr = request.getHeader(AuthnRequestStateTLSClientAuthenticationFilter.clientCertHeader);

    if (certStr != null && certStr.length() > 0
            && request.getAuthType() == SecurityRequestWrapper.VMWARE_CLIENT_CERT_AUTH) {
        ByteArrayInputStream bais = null;
        CertificateFactory cf;
        try {
            cf = CertificateFactory.getInstance("X.509");
            bais = new ByteArrayInputStream(Base64.decode(certStr));
            X509Certificate cert = (X509Certificate) cf.generateCertificate(bais);
            certChain = new X509Certificate[] { cert };
        } catch (CertificateException e1) {
            log.error("Error reading client certificate from http header. ", e1);
            ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED,
                    WebSSOError.UNAUTHORIZED, WebSSOError.INVALID_CREDENTIAL);
            t.setValidationResult(vr);
            throw new SamlServiceException("Client Certificate error.", e1);
        }
    }

    // Get from standard place of sl client cert location
    if (certChain == null || certChain.length == 0) {
        certChain = (X509Certificate[]) request
                .getAttribute(AuthnRequestStateTLSClientAuthenticationFilter.clientCertAttributeName);
    }

    if (certChain == null || certChain.length == 0) {
        ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED,
                WebSSOError.UNAUTHORIZED, WebSSOError.NO_CLIENT_CERT);
        t.setValidationResult(vr);

    } else {
        try {
            principalId = accessor.authenticate(certChain);
            Validate.notNull(principalId, "principalId");
        } catch (Exception ex) {
            // could not authenticate with the certificate
            ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED,
                    WebSSOError.UNAUTHORIZED, WebSSOError.INVALID_CREDENTIAL);
            t.setValidationResult(vr);
        }
    }

    if (principalId != null) {
        t.setPrincipalId(principalId);
        t.setAuthnMethod(AuthnMethod.TLSCLIENT);
    }
}

From source file:be.fedict.eidviewer.lib.file.Version4XMLFileCertificates.java

public List<X509Certificate> toSignChain() throws CertificateException {
    CertificateFactory certificateFactory = null;
    X509Certificate rootCert = null;
    X509Certificate citizenCert = null;
    X509Certificate signingCert = null;
    List<X509Certificate> signChain = null;

    if (getRootCertificate() == null || getCitizenCACertificate() == null || getSigningCertificate() == null)
        return null;

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

    rootCert = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(getRootCertificate().getBytes())));
    citizenCert = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(getCitizenCACertificate().getBytes())));
    signingCert = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(getSigningCertificate().getBytes())));

    signChain = new LinkedList<X509Certificate>();
    signChain.add(signingCert);//from   w  ww .j a  v  a  2s  . c om
    signChain.add(citizenCert);
    signChain.add(rootCert);

    return signChain;
}

From source file:org.bibsonomy.webapp.validation.opensocial.BibSonomyOAuthValidator.java

private PublicKey getPublicKeyFromDerCert(byte[] certObject) throws GeneralSecurityException {
    CertificateFactory fac = CertificateFactory.getInstance("X509");
    ByteArrayInputStream in = new ByteArrayInputStream(certObject);
    X509Certificate cert = (X509Certificate) fac.generateCertificate(in);
    return cert.getPublicKey();
}

From source file:org.apache.zeppelin.realm.jwt.KnoxJwtRealm.java

public static RSAPublicKey parseRSAPublicKey(String pem) throws IOException, ServletException {
    final String pemHeader = "-----BEGIN CERTIFICATE-----\n";
    final String pemFooter = "\n-----END CERTIFICATE-----";
    String fullPem = pemHeader + pem + pemFooter;
    PublicKey key = null;/*from   w ww.jav a2s .c o  m*/
    try {
        CertificateFactory fact = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream is = new ByteArrayInputStream(
                FileUtils.readFileToString(new File(pem)).getBytes("UTF8"));
        X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
        key = cer.getPublicKey();
    } catch (CertificateException ce) {
        String message = null;
        if (pem.startsWith(pemHeader)) {
            message = "CertificateException - be sure not to include PEM header "
                    + "and footer in the PEM configuration element.";
        } else {
            message = "CertificateException - PEM may be corrupt";
        }
        throw new ServletException(message, ce);
    } catch (UnsupportedEncodingException uee) {
        throw new ServletException(uee);
    } catch (IOException e) {
        throw new IOException(e);
    }
    return (RSAPublicKey) key;
}

From source file:be.fedict.hsm.client.HSMProxyClient.java

/**
 * Main constructor. To access the HSM Proxy web service, you need to have a
 * valid credential.//from w  w w  .j  a  va  2 s  . c o m
 * 
 * @param endpointAddress
 *            the HSM Proxy web service endpoint address.
 * @param credentialPrivateKey
 *            the credential private key.
 * @param credentialCertificate
 *            the corresponding credential X509 certificate.
 */
public HSMProxyClient(String endpointAddress, PrivateKey credentialPrivateKey,
        X509Certificate credentialCertificate) {
    this.endpointAddress = endpointAddress;

    DigitalSignatureService digitalSignatureService = DigitalSignatureServiceFactory.getInstance();
    this.dssPort = digitalSignatureService.getDigitalSignatureServicePort();

    BindingProvider bindingProvider = (BindingProvider) this.dssPort;
    bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointAddress);

    this.dssObjectFactory = new ObjectFactory();
    this.dsObjectFactory = new be.fedict.hsm.ws.jaxb.xmldsig.ObjectFactory();
    this.hsmObjectFactory = new be.fedict.hsm.ws.jaxb.hsm.ObjectFactory();

    try {
        this.certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("X509 certificate factory error: " + e.getMessage(), e);
    }

    Binding binding = bindingProvider.getBinding();
    List<Handler> handlerChain = binding.getHandlerChain();
    handlerChain.add(new WSSecuritySOAPHandler(credentialPrivateKey, credentialCertificate));
    binding.setHandlerChain(handlerChain);
}

From source file:be.fedict.trust.service.bean.DownloaderMDB.java

private void processColdStartMessage(ColdStartMessage coldStartMessage) {
    if (null == coldStartMessage) {
        return;//from w w w. j  a v a  2 s. c  o m
    }

    String crlUrl = coldStartMessage.getCrlUrl();
    String certUrl = coldStartMessage.getCertUrl();
    LOG.debug("cold start CRL URL: " + crlUrl);
    LOG.debug("cold start CA URL: " + certUrl);

    File crlFile = download(crlUrl);
    File certFile = download(certUrl);

    // parsing
    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        LOG.debug("certificate factory error: " + e.getMessage(), e);
        crlFile.delete();
        certFile.delete();
        return;
    }

    X509Certificate certificate = null;
    try {
        certificate = (X509Certificate) certificateFactory.generateCertificate(new FileInputStream(certFile));
    } catch (Exception e) {
        LOG.debug("error DER-parsing certificate");
        try {
            PEMReader pemReader = new PEMReader(new FileReader(certFile));
            certificate = (X509Certificate) pemReader.readObject();
            pemReader.close();
        } catch (Exception e2) {
            retry("error PEM-parsing certificate", e, certFile, crlFile);
        }
    }
    certFile.delete();

    X509CRL crl = null;
    try {
        crl = (X509CRL) certificateFactory.generateCRL(new FileInputStream(crlFile));
    } catch (Exception e) {
        retry("error parsing CRL", e, crlFile);
    }

    // first check whether the two correspond
    try {
        crl.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.error("no correspondence between CRL and CA");
        LOG.error("CRL issuer: " + crl.getIssuerX500Principal());
        LOG.debug("CA subject: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }
    LOG.debug("CRL matches CA: " + certificate.getSubjectX500Principal());

    // skip expired CAs
    Date now = new Date();
    Date notAfter = certificate.getNotAfter();
    if (now.after(notAfter)) {
        LOG.warn("CA already expired: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }

    // create database entitities
    CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(certificate);
    if (null != certificateAuthority) {
        LOG.debug("CA already in cache: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }

    /*
     * Lookup Root CA's trust point via parent certificates' CA entity.
     */
    LOG.debug(
            "Lookup Root CA's trust point via parent certificates' CA entity - Don't have Issuer's Serial Number??");
    String parentIssuerName = certificate.getIssuerX500Principal().toString();
    CertificateAuthorityEntity parentCertificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(parentIssuerName);
    if (null == parentCertificateAuthority) {
        LOG.error("CA not found for " + parentIssuerName + " ?!");
        crlFile.delete();
        return;
    }
    LOG.debug("parent CA: " + parentCertificateAuthority.getName());
    TrustPointEntity parentTrustPoint = parentCertificateAuthority.getTrustPoint();
    if (null != parentTrustPoint) {
        LOG.debug("trust point parent: " + parentTrustPoint.getName());
        LOG.debug("previous trust point fire data: " + parentTrustPoint.getFireDate());
    } else {
        LOG.debug("no parent trust point");
    }

    // create new CA
    certificateAuthority = this.certificateAuthorityDAO.addCertificateAuthority(certificate, crlUrl);

    // prepare harvesting
    certificateAuthority.setTrustPoint(parentTrustPoint);
    certificateAuthority.setStatus(Status.PROCESSING);
    if (null != certificateAuthority.getTrustPoint()
            && null == certificateAuthority.getTrustPoint().getFireDate()) {
        try {
            this.schedulingService.startTimer(certificateAuthority.getTrustPoint());
        } catch (InvalidCronExpressionException e) {
            LOG.error("invalid cron expression");
            crlFile.delete();
            return;
        }
    }

    // notify harvester
    String crlFilePath = crlFile.getAbsolutePath();
    try {
        this.notificationService.notifyHarvester(certificate.getSubjectX500Principal().toString(), crlFilePath,
                false);
    } catch (JMSException e) {
        crlFile.delete();
        throw new RuntimeException(e);
    }
}