Example usage for java.security.cert X509Certificate getSubjectX500Principal

List of usage examples for java.security.cert X509Certificate getSubjectX500Principal

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getSubjectX500Principal.

Prototype

public X500Principal getSubjectX500Principal() 

Source Link

Document

Returns the subject (subject distinguished name) value from the certificate as an X500Principal .

Usage

From source file:org.globus.gsi.TrustedCertificates.java

public synchronized void reload(String locations) {
    if (locations == null) {
        return;/*w w w . j  av  a  2 s. c o m*/
    }

    this.changed = false;

    StringTokenizer tokens = new StringTokenizer(locations, ",");
    File caDir = null;

    Map newCertSubjectDNMap = new HashMap();
    Map newSigningDNMap = new HashMap();

    while (tokens.hasMoreTokens()) {
        caDir = new File(tokens.nextToken().toString().trim());

        if (!caDir.canRead()) {
            logger.debug("Cannot read: " + caDir.getAbsolutePath());
            continue;
        }

        String caCertLocation = "file:" + caDir.getAbsolutePath();
        //            String sigPolPattern = caCertLocation + "/*.signing_policy";
        //            if (!caDir.isDirectory()) {
        //                sigPolPattern = getPolicyFileName(caCertLocation);
        //            }

        try {
            ms_trustStore = Stores.getTrustStore(caCertLocation + "/" + Stores.getDefaultCAFilesPattern());

            Collection<? extends Certificate> caCerts = KeyStoreUtil.getTrustedCertificates(ms_trustStore,
                    new X509CertSelector());
            Iterator iter = caCerts.iterator();
            while (iter.hasNext()) {
                X509Certificate cert = (X509Certificate) iter.next();
                if (!newCertSubjectDNMap.containsKey(cert.getSubjectDN().toString()))
                    newCertSubjectDNMap.put(cert.getSubjectDN().toString(), cert);
            }
        } catch (Exception e) {
            logger.warn("Failed to create trust store", e);
        }

        try {
            ms_sigPolStore = Stores
                    .getSigningPolicyStore(caCertLocation + "/" + Stores.getDefaultSigningPolicyFilesPattern());
        } catch (GeneralSecurityException e) {
            logger.warn("Failed to create signing_policy store", e);
        }

        try {
            ms_sigPolStore = Stores
                    .getSigningPolicyStore(caCertLocation + "/" + Stores.getDefaultSigningPolicyFilesPattern());
            Collection<? extends Certificate> caCerts = KeyStoreUtil.getTrustedCertificates(ms_trustStore,
                    new X509CertSelector());
            Iterator iter = caCerts.iterator();
            while (iter.hasNext()) {
                X509Certificate cert = (X509Certificate) iter.next();
                X500Principal principal = cert.getSubjectX500Principal();
                if (!newCertSubjectDNMap.containsKey(cert.getSubjectDN().toString())) {
                    continue;
                }
                SigningPolicy policy;
                try {
                    policy = ms_sigPolStore.getSigningPolicy(principal);
                } catch (Exception e) {
                    if (!invalidPolicies.contains(principal)) {
                        logger.warn("Invalid signing policy for CA certificate; skipping");
                        logger.debug("Invalid signing policy for CA certificate; skipping", e);
                        invalidPolicies.add(principal);
                    }
                    continue;
                }
                if (policy != null) {
                    newSigningDNMap.put(CertificateUtil.toGlobusID(policy.getCASubjectDN()), policy);
                } else {
                    if (!invalidPolicies.contains(principal)) {
                        logger.warn("no signing policy for ca cert " + cert.getSubjectDN());
                        invalidPolicies.add(principal);
                    }
                }
            }
        } catch (Exception e) {
            logger.warn("Failed to create signing policy store", e);
        }
    }

    this.changed = true;
    this.certSubjectDNMap = newCertSubjectDNMap;
    this.policyDNMap = newSigningDNMap;

    if (this.changed) {
        this.certList = null;
    }
}

From source file:org.atricore.idbus.capabilities.clientcertauthn.X509CertificateAuthScheme.java

/**
 * @throws SSOAuthenticationException//from   w w w  .j  a  v  a  2s.  c o m
 */
public boolean authenticate() throws SSOAuthenticationException {

    setAuthenticated(false);

    //String username = getUsername(_inputCredentials);
    X509Certificate x509Certificate = getX509Certificate(_inputCredentials);

    // Check if all credentials are present.
    if (x509Certificate == null) {

        if (logger.isDebugEnabled())
            logger.debug("X.509 Certificate not provided");

        // We don't support empty values !
        return false;
    }

    // validate certificate
    if (_validators != null) {
        for (X509CertificateValidator validator : _validators) {
            try {
                validator.validate(x509Certificate);
            } catch (X509CertificateValidationException e) {
                logger.error("Certificate is not valid!", e);
                return false;
            }
        }
    }

    // TODO STRONG-AUTH: Local certificate storage should be optional
    List<X509Certificate> knownX509Certificates = getX509Certificates(getKnownCredentials());

    StringBuffer buf = new StringBuffer("\n\tSupplied Credential: ");
    buf.append(x509Certificate.getSerialNumber().toString(16));
    buf.append("\n\t\t");
    buf.append(x509Certificate.getSubjectX500Principal().getName());
    buf.append("\n\n\tExisting Credentials: ");
    for (int i = 0; i < knownX509Certificates.size(); i++) {
        X509Certificate knownX509Certificate = knownX509Certificates.get(i);
        buf.append(i + 1);
        buf.append("\n\t\t");
        buf.append(knownX509Certificate.getSerialNumber().toString(16));
        buf.append("\n\t\t");
        buf.append(knownX509Certificate.getSubjectX500Principal().getName());
        buf.append("\n");
    }

    logger.debug(buf.toString());

    // Validate user identity ...
    boolean valid = false;
    X509Certificate validCertificate = null;
    for (X509Certificate knownX509Certificate : knownX509Certificates) {
        if (validateX509Certificate(x509Certificate, knownX509Certificate)) {
            validCertificate = knownX509Certificate;
            break;
        }
    }

    if (validCertificate == null) {
        return false;
    }

    // TODO STRONG-AUTH resolve User ID, take it from the certificate ..

    // Find UID
    // (We could just use getUID() to authenticate user
    // without previous validation against known certificates?)
    _uid = resolveUID(validCertificate);
    if (_uid == null) {
        return false;
    }

    if (logger.isDebugEnabled())
        logger.debug(
                "[authenticate()], Principal authenticated : " + x509Certificate.getSubjectX500Principal());

    // We have successfully authenticated this user.
    setAuthenticated(true);
    return true;
}

From source file:org.zuinnote.hadoop.office.format.common.parser.msexcel.MSExcelParser.java

@Override
public void parse(InputStream in) throws FormatNotUnderstoodException {
    // read xls/*  ww  w  .  jav a2  s. co  m*/

    try {
        this.currentWorkbook = WorkbookFactory.create(in, this.hocr.getPassword());
    } catch (EncryptedDocumentException | IOException e) {
        LOG.error(e);
        throw new FormatNotUnderstoodException(e.toString());
    } finally {
        if (this.in != null) {
            try {
                this.in.close();
            } catch (IOException e) {
                LOG.error(e);
            }
        }
    }
    // check if signature should be verified
    if (this.hocr.getVerifySignature()) {
        LOG.info("Verifying signature of document");
        if (!(this.currentWorkbook instanceof XSSFWorkbook)) {
            throw new FormatNotUnderstoodException(
                    "Can only verify signatures for files using the OOXML (.xlsx) format");
        } else {
            //
            OPCPackage pgk = ((XSSFWorkbook) this.currentWorkbook).getPackage();
            SignatureConfig sic = new SignatureConfig();
            sic.setOpcPackage(pgk);
            SignatureInfo si = new SignatureInfo();
            si.setSignatureConfig(sic);
            if (!si.verifySignature()) {
                throw new FormatNotUnderstoodException(
                        "Cannot verify signature of OOXML (.xlsx) file: " + this.hocr.getFileName());
            } else {
                LOG.info("Successfully verifed first part signature of OXXML (.xlsx) file: "
                        + this.hocr.getFileName());
            }
            Iterator<SignaturePart> spIter = si.getSignatureParts().iterator();
            while (spIter.hasNext()) {
                SignaturePart currentSP = spIter.next();
                if (!(currentSP.validate())) {
                    throw new FormatNotUnderstoodException(
                            "Could not validate all signature parts for file: " + this.hocr.getFileName());
                } else {
                    X509Certificate currentCertificate = currentSP.getSigner();
                    try {
                        if ((this.hocr.getX509CertificateChain().size() > 0)
                                && (!CertificateChainVerificationUtil.verifyCertificateChain(currentCertificate,
                                        this.hocr.getX509CertificateChain()))) {
                            throw new FormatNotUnderstoodException(
                                    "Could not validate signature part for principal \""
                                            + currentCertificate.getSubjectX500Principal().getName() + "\" : "
                                            + this.hocr.getFileName());
                        }
                    } catch (CertificateException | NoSuchAlgorithmException | NoSuchProviderException
                            | InvalidAlgorithmParameterException e) {
                        LOG.error("Could not validate signature part for principal \""
                                + currentCertificate.getSubjectX500Principal().getName() + "\" : "
                                + this.hocr.getFileName(), e);
                        throw new FormatNotUnderstoodException(
                                "Could not validate signature part for principal \""
                                        + currentCertificate.getSubjectX500Principal().getName() + "\" : "
                                        + this.hocr.getFileName());

                    }
                }
            }
            LOG.info("Successfully verifed all signatures of OXXML (.xlsx) file: " + this.hocr.getFileName());
        }
    }
    // formulaEvaluator
    this.formulaEvaluator = this.currentWorkbook.getCreationHelper().createFormulaEvaluator();
    // add the formulator evaluator of this file as well or we will see a strange Exception
    this.addedFormulaEvaluators.put(this.hocr.getFileName(), this.formulaEvaluator);
    this.formulaEvaluator.setIgnoreMissingWorkbooks(this.hocr.getIgnoreMissingLinkedWorkbooks());
    this.filtered = this.checkFiltered();
    this.currentRow = 0;
    if (this.sheets == null) {
        this.currentSheetName = this.currentWorkbook.getSheetAt(0).getSheetName();
    } else if (sheets.length < 1) {
        throw new FormatNotUnderstoodException("Error: no sheets selected");
    } else {
        this.currentSheetName = sheets[0];
    }
    // check skipping of additional lines
    this.currentRow += this.hocr.getSkipLines();
    // check header
    if (this.hocr.getReadHeader()) {

        LOG.debug("Reading header...");
        Object[] firstRow = this.getNext();
        if (firstRow != null) {
            this.header = new String[firstRow.length];
            for (int i = 0; i < firstRow.length; i++) {
                if ((firstRow[i] != null)
                        && (!"".equals(((SpreadSheetCellDAO) firstRow[i]).getFormattedValue()))) {
                    this.header[i] = ((SpreadSheetCellDAO) firstRow[i]).getFormattedValue();
                }
            }
            this.header = MSExcelParser.sanitizeHeaders(this.header, this.hocr.getColumnNameRegex(),
                    this.hocr.getColumnNameReplace());
        } else {
            this.header = new String[0];
        }
    }

}

From source file:org.apache.ranger.common.ServiceUtil.java

public boolean isValidateHttpsAuthentication(String serviceName, HttpServletRequest request) {
    boolean isValidAuthentication = false;
    boolean httpEnabled = PropertiesUtil.getBooleanProperty("ranger.service.http.enabled", true);
    X509Certificate[] certchain = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    String ipAddress = request.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }//w w w .  j a  v a  2s.  com
    boolean isSecure = request.isSecure();

    if (serviceName == null || serviceName.isEmpty()) {
        LOG.error("ServiceName not provided");
        throw restErrorUtil.createRESTException("Unauthorized access.",
                MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
    }

    RangerService service = null;
    try {
        service = svcStore.getServiceByName(serviceName);
    } catch (Exception e) {
        LOG.error("Requested Service not found. serviceName=" + serviceName);
        throw restErrorUtil.createRESTException("Service:" + serviceName + " not found",
                MessageEnums.DATA_NOT_FOUND);
    }
    if (service == null) {
        LOG.error("Requested Service not found. serviceName=" + serviceName);
        throw restErrorUtil.createRESTException("Service:" + serviceName + " not found",
                MessageEnums.DATA_NOT_FOUND);
    }
    if (!service.getIsEnabled()) {
        LOG.error("Requested Service is disabled. serviceName=" + serviceName);
        throw restErrorUtil.createRESTException("Unauthorized access.",
                MessageEnums.OPER_NOT_ALLOWED_FOR_STATE);
    }
    if (!httpEnabled) {
        if (!isSecure) {
            LOG.error("Unauthorized access. Only https is allowed. serviceName=" + serviceName);
            throw restErrorUtil.createRESTException("Unauthorized access -" + " only https allowed",
                    MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }
        if (certchain == null || certchain.length == 0) {
            LOG.error("Unauthorized access. Unable to get client certificate. serviceName=" + serviceName);
            throw restErrorUtil.createRESTException(
                    "Unauthorized access -" + " unable to get client certificate",
                    MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }

        // Check if common name is found in service config
        Map<String, String> configMap = service.getConfigs();
        String cnFromConfig = configMap.get("commonNameForCertificate");
        if (cnFromConfig == null || "".equals(cnFromConfig.trim())) {
            LOG.error(
                    "Unauthorized access. No common name for certificate set. Please check your service config");
            throw restErrorUtil.createRESTException(
                    "Unauthorized access. No common name for certificate set. Please check your service config",
                    MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }

        String cnFromConfigForTest = cnFromConfig;
        boolean isRegEx = cnFromConfig.toLowerCase().startsWith(REGEX_PREFIX_STR);
        if (isRegEx) {
            cnFromConfigForTest = cnFromConfig.substring(REGEX_PREFIX_STR_LENGTH);
        }

        // Perform SAN validation
        try {
            Collection<List<?>> subjectAltNames = certchain[0].getSubjectAlternativeNames();
            if (subjectAltNames != null) {
                for (List<?> sanItem : subjectAltNames) {
                    if (sanItem.size() == 2) {
                        Integer sanType = (Integer) sanItem.get(0);
                        String sanValue = (String) sanItem.get(1);
                        if ((sanType == 2 || sanType == 7)
                                && (matchNames(sanValue, cnFromConfigForTest, isRegEx))) {
                            if (LOG.isDebugEnabled())
                                LOG.debug("Client Cert verification successful, matched SAN:" + sanValue);
                            isValidAuthentication = true;
                            break;
                        }
                    }
                }
            }
        } catch (Throwable e) {
            LOG.error("Unauthorized access. Error getting SAN from certificate", e);
            throw restErrorUtil.createRESTException(
                    "Unauthorized access - Error getting SAN from client certificate",
                    MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }

        // Perform common name validation only if SAN validation did not succeed
        if (!isValidAuthentication) {
            String commonName = null;
            if (certchain != null) {
                X509Certificate clientCert = certchain[0];
                String dn = clientCert.getSubjectX500Principal().getName();
                try {
                    LdapName ln = new LdapName(dn);
                    for (Rdn rdn : ln.getRdns()) {
                        if (rdn.getType().equalsIgnoreCase("CN")) {
                            commonName = rdn.getValue() + "";
                            break;
                        }
                    }
                    if (commonName == null) {
                        LOG.error("Unauthorized access. CName is null. serviceName=" + serviceName);
                        throw restErrorUtil.createRESTException(
                                "Unauthorized access - Unable to find Common Name from [" + dn + "]",
                                MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
                    }
                } catch (InvalidNameException e) {
                    LOG.error("Invalid Common Name. CName=" + commonName + ", serviceName=" + serviceName, e);
                    throw restErrorUtil.createRESTException("Unauthorized access - Invalid Common Name",
                            MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
                }
            }
            if (commonName != null) {
                if (matchNames(commonName, cnFromConfigForTest, isRegEx)) {
                    if (LOG.isDebugEnabled())
                        LOG.debug("Client Cert verification successful, matched CN " + commonName + " with "
                                + cnFromConfigForTest + ", wildcard match = " + isRegEx);
                    isValidAuthentication = true;
                }

                if (!isValidAuthentication) {
                    LOG.error("Unauthorized access. expected [" + cnFromConfigForTest + "], found ["
                            + commonName + "], serviceName=" + serviceName);
                    throw restErrorUtil.createRESTException("Unauthorized access. expected ["
                            + cnFromConfigForTest + "], found [" + commonName + "]",
                            MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
                }
            }
        }
    } else {
        isValidAuthentication = true;
    }
    return isValidAuthentication;
}

From source file:org.apache.ws.security.handler.WSHandler.java

/**
 * Evaluate whether a given certificate should be trusted.
 * Hook to allow subclasses to implement custom validation methods however they see fit.
 * <p/>/*from  w w w . j a v a 2s. c  o m*/
 * Policy used in this implementation:
 * 1. Search the keystore for the transmitted certificate
 * 2. Search the keystore for a connection to the transmitted certificate
 * (that is, search for certificate(s) of the issuer of the transmitted certificate
 * 3. Verify the trust path for those certificates found because the search for the issuer 
 * might be fooled by a phony DN (String!)
 *
 * @param cert the certificate that should be validated against the keystore
 * @return true if the certificate is trusted, false if not (AxisFault is thrown for exceptions
 * during CertPathValidation)
 * @throws WSSecurityException
 */
protected boolean verifyTrust(X509Certificate cert, RequestData reqData) throws WSSecurityException {

    // If no certificate was transmitted, do not trust the signature
    if (cert == null) {
        return false;
    }

    String[] aliases = null;
    String alias = null;
    X509Certificate[] certs;

    String subjectString = cert.getSubjectX500Principal().getName();
    String issuerString = cert.getIssuerX500Principal().getName();
    BigInteger issuerSerial = cert.getSerialNumber();

    if (doDebug) {
        log.debug("WSHandler: Transmitted certificate has subject " + subjectString);
        log.debug("WSHandler: Transmitted certificate has issuer " + issuerString + " (serial " + issuerSerial
                + ")");
    }

    // FIRST step
    // Search the keystore for the transmitted certificate

    // Search the keystore for the alias of the transmitted certificate
    try {
        alias = reqData.getSigCrypto().getAliasForX509Cert(issuerString, issuerSerial);
    } catch (WSSecurityException ex) {
        throw new WSSecurityException("WSHandler: Could not get alias for certificate with " + subjectString,
                ex);
    }

    if (alias != null) {
        // Retrieve the certificate for the alias from the keystore
        try {
            certs = reqData.getSigCrypto().getCertificates(alias);
        } catch (WSSecurityException ex) {
            throw new WSSecurityException("WSHandler: Could not get certificates for alias " + alias, ex);
        }

        // If certificates have been found, the certificates must be compared
        // to ensure against phony DNs (compare encoded form including signature)
        if (certs != null && certs.length > 0 && cert.equals(certs[0])) {
            if (doDebug) {
                log.debug("Direct trust for certificate with " + subjectString);
            }
            return true;
        }
    } else {
        if (doDebug) {
            log.debug("No alias found for subject from issuer with " + issuerString + " (serial " + issuerSerial
                    + ")");
        }
    }

    // SECOND step
    // Search for the issuer of the transmitted certificate in the keystore

    // Search the keystore for the alias of the transmitted certificates issuer
    try {
        aliases = reqData.getSigCrypto().getAliasesForDN(issuerString);
    } catch (WSSecurityException ex) {
        throw new WSSecurityException("WSHandler: Could not get alias for certificate with " + issuerString,
                ex);
    }

    // If the alias has not been found, the issuer is not in the keystore
    // As a direct result, do not trust the transmitted certificate
    if (aliases == null || aliases.length < 1) {
        if (doDebug) {
            log.debug("No aliases found in keystore for issuer " + issuerString + " of certificate for "
                    + subjectString);
        }
        return false;
    }

    // THIRD step
    // Check the certificate trust path for every alias of the issuer found in the keystore
    for (int i = 0; i < aliases.length; i++) {
        alias = aliases[i];

        if (doDebug) {
            log.debug("Preparing to validate certificate path with alias " + alias + " for issuer "
                    + issuerString);
        }

        // Retrieve the certificate(s) for the alias from the keystore
        try {
            certs = reqData.getSigCrypto().getCertificates(alias);
        } catch (WSSecurityException ex) {
            throw new WSSecurityException("WSHandler: Could not get certificates for alias " + alias, ex);
        }

        // If no certificates have been found, there has to be an error:
        // The keystore can find an alias but no certificate(s)
        if (certs == null || certs.length < 1) {
            throw new WSSecurityException("WSHandler: Could not get certificates for alias " + alias);
        }

        // Form a certificate chain from the transmitted certificate
        // and the certificate(s) of the issuer from the keystore
        // First, create new array
        X509Certificate[] x509certs = new X509Certificate[certs.length + 1];
        // Then add the first certificate ...
        x509certs[0] = cert;
        // ... and the other certificates
        for (int j = 0; j < certs.length; j++) {
            x509certs[j + 1] = certs[j];
        }
        certs = x509certs;

        // Use the validation method from the crypto to check whether the subjects' 
        // certificate was really signed by the issuer stated in the certificate
        try {
            if (reqData.getSigCrypto().validateCertPath(certs)) {
                if (doDebug) {
                    log.debug("WSHandler: Certificate path has been verified for certificate " + "with subject "
                            + subjectString);
                }
                return true;
            }
        } catch (WSSecurityException ex) {
            throw new WSSecurityException("WSHandler: Certificate path verification failed for certificate "
                    + "with subject " + subjectString, ex);
        }
    }

    if (doDebug) {
        log.debug("WSHandler: Certificate path could not be verified for " + "certificate with subject "
                + subjectString);
    }
    return false;
}

From source file:homenetapp.HomeNetAppGui.java

private void checkClientCert() {
    try {//w  w w  .  j  a v a2  s.  co m
        URL url = new URL("https://" + homenetapp.clientServer + "/");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.connect();
        Certificate[] certs = conn.getServerCertificates();

        //System.out.println("Cert Chain Length: "+certs.length);

        Certificate c = certs[0];
        X509Certificate xc = (X509Certificate) c;

        String[] from = homenetapp.splitTokens(xc.getIssuerX500Principal().getName(), "=, ");
        String[] to = homenetapp.splitTokens(xc.getSubjectX500Principal().getName(), "=, ");

        certPropertiesLabel.setText("<html>Issued by: " + from[1] + "<br>For: " + to[1] + "<br>Expires: "
                + xc.getNotAfter() + "</html>");

        System.out.println("Cert: " + c.getType());

        System.out.println("Not After: " + xc.getNotAfter());
        System.out.println("Subject DN: " + xc.getSubjectX500Principal());
        System.out.println("Issuer DN: " + xc.getIssuerX500Principal());
        System.out.println("getSigAlgName: " + xc.getSigAlgName());

    } catch (Exception e) {
        certPropertiesLabel.setText("Failed to load certficate");
    }

}

From source file:net.sf.keystore_explorer.gui.actions.SignCsrAction.java

/**
 * Do action.//from   w  w  w  .  j  a  v a  2  s .  c om
 */
@Override
protected void doAction() {
    FileOutputStream fos = null;
    File caReplyFile = null;

    try {
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStoreState currentState = history.getCurrentState();

        String alias = kseFrame.getSelectedEntryAlias();

        Password password = getEntryPassword(alias, currentState);

        if (password == null) {
            return;
        }

        KeyStore keyStore = currentState.getKeyStore();

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
        Certificate[] certs = keyStore.getCertificateChain(alias);

        KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey);

        File csrFile = chooseCsrFile();
        if (csrFile == null) {
            return;
        }

        PKCS10CertificationRequest pkcs10Csr = null;
        Spkac spkacCsr = null;

        try {
            CryptoFileType fileType = CryptoFileUtil.detectFileType(new FileInputStream(csrFile));
            if (fileType == CryptoFileType.PKCS10_CSR) {
                pkcs10Csr = Pkcs10Util.loadCsr(new FileInputStream(csrFile));

                if (!Pkcs10Util.verifyCsr(pkcs10Csr)) {
                    JOptionPane.showMessageDialog(frame,
                            res.getString("SignCsrAction.NoVerifyPkcs10Csr.message"),
                            res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
                    return;
                }
            } else if (fileType == CryptoFileType.SPKAC_CSR) {
                spkacCsr = new Spkac(new FileInputStream(csrFile));

                if (!spkacCsr.verify()) {
                    JOptionPane.showMessageDialog(frame,
                            res.getString("SignCsrAction.NoVerifySpkacCsr.message"),
                            res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
                    return;
                }
            } else {
                JOptionPane.showMessageDialog(frame,
                        MessageFormat.format(res.getString("SignCsrAction.FileNotRecognisedType.message"),
                                csrFile),
                        res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
                return;
            }
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(frame,
                    MessageFormat.format(res.getString("SignCsrAction.NotFile.message"), csrFile),
                    res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
            return;
        } catch (Exception ex) {
            String problemStr = MessageFormat.format(res.getString("SignCsrAction.NoOpenCsr.Problem"),
                    csrFile.getName());

            String[] causes = new String[] { res.getString("SignCsrAction.NotCsr.Cause"),
                    res.getString("SignCsrAction.CorruptedCsr.Cause") };

            Problem problem = new Problem(problemStr, causes, ex);

            DProblem dProblem = new DProblem(frame, res.getString("SignCsrAction.ProblemOpeningCsr.Title"),
                    problem);
            dProblem.setLocationRelativeTo(frame);
            dProblem.setVisible(true);

            return;
        }

        X509Certificate[] signingChain = X509CertUtil
                .orderX509CertChain(X509CertUtil.convertCertificates(certs));
        X509Certificate signingCert = signingChain[0];

        PublicKey publicKey = null;
        X500Name subject = null;
        DSignCsr dSignCsr = null;
        Provider provider = history.getExplicitProvider();

        if (pkcs10Csr != null) {
            publicKey = new JcaPKCS10CertificationRequest(pkcs10Csr).getPublicKey();
            subject = pkcs10Csr.getSubject();

            dSignCsr = new DSignCsr(frame, pkcs10Csr, csrFile, privateKey, keyPairType, signingCert, provider);
        } else {
            publicKey = spkacCsr.getPublicKey();
            subject = spkacCsr.getSubject().getName();

            dSignCsr = new DSignCsr(frame, spkacCsr, csrFile, privateKey, keyPairType, signingCert, provider);
        }

        dSignCsr.setLocationRelativeTo(frame);
        dSignCsr.setVisible(true);

        X509CertificateVersion version = dSignCsr.getVersion();
        SignatureType signatureType = dSignCsr.getSignatureType();
        long validityPeriod = dSignCsr.getValidityPeriod();
        BigInteger serialNumber = dSignCsr.getSerialNumber();
        caReplyFile = dSignCsr.getCaReplyFile();
        X509ExtensionSet extensions = dSignCsr.getExtensions();

        if (version == null) {
            return;
        }

        X500Name issuer = X500NameUtils.x500PrincipalToX500Name(signingCert.getSubjectX500Principal());

        // CA Reply is a cert with subject from CSR and issuer from signing cert's subject
        X509CertificateGenerator generator = new X509CertificateGenerator(version);
        X509Certificate caReplyCert = generator.generate(subject, issuer, validityPeriod, publicKey, privateKey,
                signatureType, serialNumber, extensions, provider);

        X509Certificate[] caReplyChain = new X509Certificate[signingChain.length + 1];

        caReplyChain[0] = caReplyCert;

        // Add all of the signing chain to the reply
        System.arraycopy(signingChain, 0, caReplyChain, 1, signingChain.length);

        byte[] caCertEncoded = X509CertUtil.getCertsEncodedPkcs7(caReplyChain);

        fos = new FileOutputStream(caReplyFile);
        fos.write(caCertEncoded);
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(frame,
                MessageFormat.format(res.getString("SignJarAction.NoWriteFile.message"), caReplyFile),
                res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
        return;
    } catch (Exception ex) {
        DError.displayError(frame, ex);
        return;
    } finally {
        IOUtils.closeQuietly(fos);
    }

    JOptionPane.showMessageDialog(frame, res.getString("SignCsrAction.SignCsrSuccessful.message"),
            res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.INFORMATION_MESSAGE);
}

From source file:edu.washington.iam.registry.ws.RelyingPartyController.java

private RPSession processRequestInfo(HttpServletRequest request, HttpServletResponse response,
        boolean canLogin) {
    RPSession session = new RPSession();
    session.isAdmin = false;/* www .java  2s.  c o  m*/
    session.adminRole = false;
    session.isUWLogin = false;
    session.isProxy = false;
    String reloginPath = null;

    log.info("RP new session =============== path=" + request.getPathInfo());

    session.isMobile = false;
    Device currentDevice = DeviceUtils.getCurrentDevice(request);
    if (currentDevice != null)
        session.isMobile = currentDevice.isMobile();
    log.debug("mobile? " + session.isMobile);

    // see if logged in (browser has login cookie; cert user has cert)

    int resetAdmin = 1; // on expired or no cookie, reset the 'admin role cookei'
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(loginCookie)) {
                log.debug("got cookie " + cookies[i].getName());
                String cookieStr = RPCrypt.decode(cookies[i].getValue());
                if (cookieStr == null)
                    continue;
                String[] cookieData = cookieStr.split(";");
                if (cookieData.length == 5) {

                    if (cookieData[3].charAt(0) == '2')
                        session.authn2 = true;

                    log.debug("login time = " + cookieData[4]);
                    long cSec = new Long(cookieData[4]);
                    long nSec = new Date().getTime() / 1000;
                    if (cookieData[1].indexOf("@") < 0)
                        session.isUWLogin = true; // klugey way to know UW people
                    session.timeLeft = (cSec + standardLoginSec) - nSec;
                    if (session.timeLeft > 0) {
                        if ((nSec > (cSec + secureLoginSec)) && session.authn2) {
                            log.debug("secure expired");
                            session.authn2 = false;
                            resetAdmin = 2;
                        }

                        // cookie OK
                        session.remoteUser = cookieData[1];
                        session.xsrfCode = cookieData[2];
                        log.debug("login for " + session.remoteUser);
                        if (session.authn2)
                            log.debug("secure login");
                        if (adminGroup.isMember(session.remoteUser)) {
                            log.debug("is admin");
                            session.isAdmin = true;
                        }

                        if (resetAdmin == 1)
                            resetAdmin = 0;
                    } else {
                        log.debug("cookie expired for " + cookieData[1]);
                        // remember where they logged in last
                        if (session.isUWLogin)
                            reloginPath = browserRootPath + request.getServletPath() + standardLoginPath;
                        else if (cookieData[1].indexOf("gmail.com") > 0)
                            reloginPath = browserRootPath + request.getServletPath() + googleLoginPath;
                        // let others choose
                    }
                }
            } else if (cookies[i].getName().equals(roleCookie) && cookies[i].getValue().equals("a")) {
                log.debug("got role=admin cookie");
                session.adminRole = true;
            }
        }
    }

    if (resetAdmin > 0) {
        log.debug("clearing expired admn request");
        session.adminRole = false;
        Cookie c = new Cookie(roleCookie, "x");
        c.setSecure(true);
        c.setPath("/");
        response.addCookie(c);
    }

    if (session.remoteUser != null) {
        // ok, is a logged in browser
        session.viewType = "browser";
        session.isBrowser = true;
        session.rootPath = browserRootPath;

    } else {
        // maybe is cert client
        // use the CN portion of the DN as the client userid
        X509Certificate[] certs = (X509Certificate[]) request
                .getAttribute("javax.servlet.request.X509Certificate");
        if (certs != null) {
            session.viewType = "xml";
            session.isBrowser = false;
            session.rootPath = certRootPath;
            X509Certificate cert = certs[0];
            String dn = cert.getSubjectX500Principal().getName();
            session.remoteUser = dn.replaceAll(".*CN=", "").replaceAll(",.*", "");
            log.info(".. remote user by cert, dn=" + dn + ", cn=" + session.remoteUser);
            session.altNames = new Vector();
            try {
                Collection altNames = cert.getSubjectAlternativeNames();
                if (altNames != null) {
                    for (Iterator i = altNames.iterator(); i.hasNext();) {
                        List item = (List) i.next();
                        Integer type = (Integer) item.get(0);
                        if (type.intValue() == 2) {
                            String altName = (String) item.get(1);
                            log.info(".. adding altname " + altName);
                            session.altNames.add(altName);
                        }
                    }
                } else
                    session.altNames.add(session.remoteUser); // rules say cn meaningful only when altnames not present
            } catch (CertificateParsingException e) {
                log.info(".. altname parse failed: " + e);
            }
        }

    }

    /* send missing remoteUser to login */

    if (session.remoteUser == null) {
        if (canLogin) {
            if (reloginPath != null) {
                log.debug("no user yet:  relogin at " + reloginPath);
                try {
                    response.sendRedirect(reloginPath);
                } catch (IOException e) {
                    log.error("redirect: " + e);
                }
            }
            log.debug("no user yet:  send to choose");
            session.mv = loginChooserMV(session, request, response);
            return session;
        }
        return null;
    }

    // only admins can get admin role
    if (!session.isAdmin)
        session.adminRole = false;
    if (session.adminRole && !session.authn2) { // admin needs 2f
        log.debug("need secure login for admin role");
        sendToLogin(request, response, secureLoginPath);
    }
    session.servletPath = request.getServletPath();
    session.remoteAddr = request.getRemoteAddr();

    // etag headers
    session.ifMatch = getLongHeader(request, "If-Match");
    session.ifNoneMatch = getLongHeader(request, "If-None-Match");
    log.info("tags: match=" + session.ifMatch + ", nonematch=" + session.ifNoneMatch);

    log.info("user: " + session.remoteUser);
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max_age=1");
    response.setHeader("X-UA-Compatible", "IE=7");

    log.info("user: " + session.remoteUser);
    if (session.viewType.equals("browser") && session.isMobile)
        session.viewType = "mobile";
    return session;
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private boolean verifyCertificate(X509Certificate cert) {
    try {// w w w . j  a va 2s . co  m
        String keypass = "";
        String keystorename = System.getProperty("deployment.user.security.trusted.certs");
        if (keystorename == null) {
            throw new IOException("No trusted certs keystore");
        }

        KeyStore keystore = KeyStore.getInstance("JKS", "SUN");
        File file = new File(keystorename);
        if (!file.exists()) {
            keystore.load(null, keypass.toCharArray());
        } else {
            keystore.load(new FileInputStream(keystorename), keypass.toCharArray());
        }
        boolean isInStore = false;
        Enumeration<String> aliases = keystore.aliases();
        while (aliases.hasMoreElements() && !isInStore) {
            String alias = aliases.nextElement();
            Certificate certificate = keystore.getCertificate(alias);
            if (certificate != null) {
                if (certificate.equals(cert)) {
                    isInStore = true;
                }
            }
        }
        if (!isInStore) {
            int result = JOptionPane.showConfirmDialog(null,
                    "Do you want to trust the bridge implementation " + "signed by\n"
                            + cert.getSubjectX500Principal().getName(),
                    "Trust source?", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                keystore.setEntry("deploymentusercert-" + System.currentTimeMillis(),
                        new KeyStore.TrustedCertificateEntry(cert), null);
                FileOutputStream output = new FileOutputStream(keystorename);
                keystore.store(output, keypass.toCharArray());
                output.close();
                return true;
            }
            return false;
        }
        return true;
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return false;
}

From source file:mitm.common.security.crl.PKIXRevocationChecker.java

@Override
public RevocationResult getRevocationStatus(CertPath certPath, TrustAnchor trustAnchor, Date now)
        throws CRLException {
    Check.notNull(certPath, "certPath");
    Check.notNull(trustAnchor, "trustAnchor");

    List<? extends Certificate> certificates = certPath.getCertificates();

    RevocationResult revocationResult = new RevocationResultImpl(certificates.size());

    /* /*  w w  w  .  j  a  v a  2 s  . c om*/
     * Step through all the certificates in the path and check the revocation status of all
     * the certificates in the path.
     */
    for (int i = 0; i < certificates.size(); i++) {
        X509Certificate certificate = toX509Certificate(certificates.get(i));

        PublicKey issuerPublicKey;
        X500Principal issuer;
        X509Certificate issuerCertificate;

        /*
         * we need to get the issuer of the current certificate
         * check if there is a next certificate in the path or that we must use the TrustAnchor
         */
        if ((i + 1) == certificates.size()) {
            /* this was the last entry from the path so we must use the trust anchor */
            if (trustAnchor.getTrustedCert() != null) {
                issuerCertificate = toX509Certificate(trustAnchor.getTrustedCert());
                issuerPublicKey = issuerCertificate.getPublicKey();
                issuer = issuerCertificate.getSubjectX500Principal();
            } else {
                /* the TrustAnchor does not contain a certificate but only an issuer and public key */
                issuerCertificate = null;
                issuerPublicKey = trustAnchor.getCAPublicKey();
                issuer = trustAnchor.getCA();
            }
        } else {
            /* get next entry from path ie. the issuer of the current certificate */
            issuerCertificate = toX509Certificate(certificates.get(i + 1));
            issuerPublicKey = issuerCertificate.getPublicKey();
            issuer = issuerCertificate.getSubjectX500Principal();
        }

        /*
         * sanity check to make sure the CertPath is ordered from end -> final CA
         * ie that the next certificate signed the previous certificate
         */
        verifyCertificate(certificate, issuerPublicKey);

        /* 
         * Sanity check. The issuer principal field of the certificate currently checked should 
         * normally be equal to the issuer principal.
         */
        if (!certificate.getIssuerX500Principal().equals(issuer)) {
            logger.warn("Certificate issuer field is not equal to issuer.");
        }

        if (issuerCertificate != null) {
            Set<KeyUsageType> keyUsage = X509CertificateInspector.getKeyUsage(issuerCertificate);

            /* 
             * check if issuer is allowed to issue CRLs (only when we have an issuerCertificate, and
             * a key usage extension) 
             */
            if (keyUsage != null && !keyUsage.contains(KeyUsageType.CRLSIGN)) {
                logger.debug("Issuer is not allowed to issue CRLs.");

                /*
                 * We will return UNKNOWN status.
                 */
                RevocationDetailImpl detail = new RevocationDetailImpl(RevocationStatus.UNKNOWN);

                revocationResult.getDetails()[i] = detail;

                /* there is no need to continue because issuer is not allowed to issue CRLs */
                break;
            }
        }

        X509CRLSelector crlSelector = new X509CRLSelector();

        /* create a selector to find all relevant CRLs that were issued to the same issuer as the certificate */
        crlSelector.addIssuer(issuer);

        try {
            List<X509CRL> crls = findCRLs(certificate, crlSelector, issuerPublicKey, now);

            RevocationDetail detail = getRevocationDetail(crls, certificate, issuerCertificate, issuerPublicKey,
                    now);

            revocationResult.getDetails()[i] = detail;

            if (detail.getStatus() == RevocationStatus.REVOKED) {
                logger.warn("Certificate is revoked.");

                if (logger.isDebugEnabled()) {
                    logger.debug("Revoked certificate: " + certificate);
                }

                /* there is no need to continue because the CRL is revoked */
                break;
            }
        } catch (NoSuchProviderException e) {
            throw new NoSuchProviderRuntimeException(e);
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Revocation status for CertPath " + certPath + " and TrustAnchor " + trustAnchor + " is "
                + revocationResult);
    }

    return revocationResult;
}