Example usage for java.security.cert X509Certificate getSubjectDN

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

Introduction

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

Prototype

public abstract Principal getSubjectDN();

Source Link

Document

Denigrated, replaced by #getSubjectX500Principal() .

Usage

From source file:com.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java

public static List<CertificateInfo> getCertificate(String host, int port) throws PhrescoException {
    List<CertificateInfo> certificates = new ArrayList<CertificateInfo>();
    CertificateInfo info;/*w  ww. j a v a2  s.c  o  m*/
    try {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            socket.startHandshake();
            socket.close();
        } catch (SSLException e) {

        }
        X509Certificate[] chain = tm.chain;
        for (int i = 0; i < chain.length; i++) {
            X509Certificate x509Certificate = chain[i];
            String subjectDN = x509Certificate.getSubjectDN().getName();
            String[] split = subjectDN.split(",");
            info = new CertificateInfo();
            info.setSubjectDN(subjectDN);
            info.setDisplayName(split[0]);
            info.setCertificate(x509Certificate);
            certificates.add(info);
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return certificates;
}

From source file:org.tolven.config.model.CredentialManager.java

public void processTrustStore(TrustStoreDetail trustStoreDetail) {
    try {//from w w w  .  j a  v a 2s  .  com
        Set<X509Certificate> newTrustStoreCerts = new HashSet<X509Certificate>();
        Set<X509Certificate> previousTrustStoreCerts = new HashSet<X509Certificate>();
        Set<X509Certificate> resultingTrustStoreCerts = new HashSet<X509Certificate>();
        for (TrustStoreCertificateDetail trustStoreCertificateDetail : trustStoreDetail.getCertificate()) {
            CertificateGroupDetail certGroup = getTolvenConfigWrapper()
                    .getCredentialGroup(trustStoreCertificateDetail.getRefId());
            if (certGroup == null) {
                throw new RuntimeException("The trusted group " + trustStoreCertificateDetail.getRefId()
                        + " in truststore " + trustStoreDetail.getId() + " does not exist");
            }
            X509Certificate trustStoreX509Certificate = getTolvenConfigWrapper().getX509Certificate(certGroup);
            newTrustStoreCerts.add(trustStoreX509Certificate);
        }
        File trustStoreFile = new File(trustStoreDetail.getSource());
        if (TolvenConfigWrapper.TOLVEN_CREDENTIAL_FORMAT_PEM.equals(trustStoreDetail.getFormat())) {
            if (trustStoreFile.exists()) {
                previousTrustStoreCerts = getTolvenConfigWrapper().getX509Certificates(trustStoreFile);
                for (X509Certificate cert : previousTrustStoreCerts) {
                    resultingTrustStoreCerts.add(cert);
                }
            }
            // And now for what Java calls a Set intersection
            resultingTrustStoreCerts.retainAll(newTrustStoreCerts);
            if (resultingTrustStoreCerts.size() != newTrustStoreCerts.size()
                    || !resultingTrustStoreCerts.containsAll(newTrustStoreCerts)) {
                FileOutputStream out = null;
                try {
                    out = new FileOutputStream(trustStoreFile);
                    for (X509Certificate x509Certificate : newTrustStoreCerts) {
                        out.write(convertToPEMBytes(x509Certificate));
                    }
                } finally {
                    if (out != null) {
                        out.close();
                    }
                }
                logger.info("Created truststore: " + trustStoreDetail.getId());
            }
        } else if (TolvenConfigWrapper.TOLVEN_CREDENTIAL_FORMAT_JKS.equals(trustStoreDetail.getFormat())
                || TolvenConfigWrapper.TOLVEN_CREDENTIAL_FORMAT_PKCS12.equals(trustStoreDetail.getFormat())) {
            char[] truststorepass = getPasswordHolder().getPassword(trustStoreDetail.getId());
            if (trustStoreFile.exists()) {
                KeyStore trustStore = getTolvenConfigWrapper().getKeyStore(truststorepass, trustStoreFile,
                        trustStoreDetail.getFormat());
                Enumeration<String> enumeration = trustStore.aliases();
                while (enumeration.hasMoreElements()) {
                    String alias = enumeration.nextElement();
                    X509Certificate cert = (X509Certificate) trustStore.getCertificate(alias);
                    previousTrustStoreCerts.add(cert);
                    resultingTrustStoreCerts.add(cert);
                }
            }
            // And now for what Java calls a Set intersection
            resultingTrustStoreCerts.retainAll(newTrustStoreCerts);
            if (resultingTrustStoreCerts.size() != newTrustStoreCerts.size()
                    || !resultingTrustStoreCerts.containsAll(newTrustStoreCerts)) {
                KeyStore trustStore = KeyStore.getInstance(trustStoreDetail.getFormat());
                trustStore.load(null, truststorepass);
                for (X509Certificate newCert : newTrustStoreCerts) {
                    String alias = newCert.getSubjectDN().getName();
                    trustStore.setCertificateEntry(alias, newCert);
                }
                trustStoreFile.getParentFile().mkdirs();
                write(trustStore, trustStoreFile, truststorepass);
                logger.info("Created truststore: " + trustStoreDetail.getId());
            }
        } else {
            throw new RuntimeException("Unrecognized keystore format: " + trustStoreDetail.getFormat());
        }
    } catch (Exception ex) {
        throw new RuntimeException("Failed to process truststore: " + trustStoreDetail.getId(), ex);
    }
}

From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java

private Certificate createCertificate(MultipartFile certificate, BindingResult result) {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Certificate cert = new Certificate();
    if (certificate != null && certificate.getSize() > 0) {

        try {//from   ww w.  j a v a 2 s .c  o m
            PEMReader r = new PEMReader(
                    new InputStreamReader(new ByteArrayInputStream(certificate.getBytes())));
            Object certObj = r.readObject();

            long reference = System.currentTimeMillis();

            // validate certificate
            if (certObj instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) certObj;
                BigInteger serialNumber = x509cert.getSerialNumber();

                String issuerDn = x509cert.getIssuerDN().getName();
                String subjectDn = x509cert.getSubjectDN().getName();

                cert.setCertificate(certificate.getBytes());
                cert.setSerialNumber(serialNumber.toString());
                cert.setIssuer(issuerDn);
                cert.setSubject(subjectDn);
                cert.setSubjectCommonName(extractFromDn(subjectDn, "CN"));
                cert.setSubjectOrganization(extractFromDn(subjectDn, "O"));
                cert.setSubjectOrganizationUnit(extractFromDn(subjectDn, "OU"));
                cert.setSubjectLocation(extractFromDn(subjectDn, "L"));
                cert.setSubjectCountry(extractFromDn(subjectDn, "C"));
                cert.setNotAfter(x509cert.getNotAfter());
                cert.setNotBefore(x509cert.getNotBefore());
            } else {
                String line;
                StringBuilder certString = new StringBuilder();
                while ((line = r.readLine()) != null) {
                    certString.append(line + "\n");
                }
                log.warn(
                        "Bad certificate [{}]: Provided certificate was of the wrong type: {}. Certificate: \n{}",
                        new Object[] { reference, certObj, certString.toString() });
                result.rejectValue("certificates", "invalid.certificate",
                        "Certifikatet r ej giltigt (Reference: " + reference + ")");
            }

            r.close();
        } catch (IOException e) {
            log.warn("Bad certificate");
            result.rejectValue("certificates", "invalid.certificate", "Certifikatet r ej giltigt ");
        }
    }
    return cert;
}

From source file:org.ejbca.extra.ra.ScepRAServlet.java

private void service(String operation, String message, String remoteAddr, HttpServletResponse response)
        throws IOException {
    try {//from  w  w  w  .  j  a v a  2 s . co m
        if ((operation == null) || (message == null)) {
            log.error("Got request missing operation and/or message parameters.");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Parameters 'operation' and 'message' must be supplied!");
            return;
        }
        log.debug("Got request '" + operation + "'");
        log.debug("Message: " + message);
        log.debug("Operation is : " + operation);

        String alias = scepraks.getAlias();
        log.debug("SCEP RA Keystore alias : " + alias);
        KeyStore raks = scepraks.getKeyStore();
        Certificate[] chain = raks.getCertificateChain(alias);
        X509Certificate cacert = null;
        if (chain.length > 1) {
            // This should absolutely be more than one!
            cacert = (X509Certificate) chain[1];
        } else {
            log.error(
                    "Certificate chain in RA keystore is only 1 certificate long! This is en error, because there should also be CA certificates.");
        }
        X509Certificate racert = (X509Certificate) raks.getCertificate(alias);
        String kspwd = ExtraConfiguration.instance()
                .getString(ExtraConfiguration.SCEPKEYSTOREPWD + keyStoreNumber);
        PrivateKey rapriv = (PrivateKey) raks.getKey(alias, kspwd.toCharArray());

        if (operation.equals("PKIOperation")) {
            byte[] scepmsg = Base64.decode(message.getBytes());

            // Read the message end get the cert, this also checks authorization
            boolean includeCACert = true;
            if (StringUtils.equals("0", getInitParameter("includeCACert"))) {
                includeCACert = false;
            }

            byte[] reply = null;
            ScepRequestMessage reqmsg = new ScepRequestMessage(scepmsg, includeCACert);
            String transId = reqmsg.getTransactionId();
            log.debug("Received a message of type: " + reqmsg.getMessageType());
            if (reqmsg.getMessageType() == ScepRequestMessage.SCEP_TYPE_GETCERTINITIAL) {
                log.info("Received a GetCertInitial message from host: " + remoteAddr);
                Message msg = null;
                try {
                    msg = msgHome.findByMessageId(transId);
                } catch (Exception e) {
                    // TODO: internal resources
                    log.info("Error looking for message with transId " + transId + " :", e);
                }
                if (msg != null) {
                    if (msg.getStatus().equals(Message.STATUS_PROCESSED)) {
                        log.debug("Request is processed with status: " + msg.getStatus());
                        SubMessages submessagesresp = msg.getSubMessages(null, null, null);
                        Iterator<ISubMessage> iter = submessagesresp.getSubMessages().iterator();
                        PKCS10Response resp = (PKCS10Response) iter.next();
                        // create proper ScepResponseMessage
                        IResponseMessage ret = reqmsg.createResponseMessage(
                                org.ejbca.core.protocol.scep.ScepResponseMessage.class, reqmsg, racert, rapriv,
                                cryptProvider);
                        ret.setCACert(cacert);
                        X509Certificate respCert = resp.getCertificate();
                        if (resp.isSuccessful() && (respCert != null)) {
                            ret.setCertificate(respCert);
                        } else {
                            ret.setStatus(ResponseStatus.FAILURE);
                            ret.setFailInfo(FailInfo.BAD_REQUEST);
                            String failText = resp.getFailInfo();
                            ret.setFailText(failText);
                        }
                        ret.create();
                        reply = ret.getResponseMessage();
                    } else {
                        log.debug("Request is not yet processed, status: " + msg.getStatus());
                        reply = createPendingResponseMessage(reqmsg, racert, rapriv, cryptProvider)
                                .getResponseMessage();
                        log.debug("Responding with pending response, still pending.");
                    }
                } else {
                    // User doesn't exist
                }
            } else {
                if (reqmsg.getMessageType() == ScepRequestMessage.SCEP_TYPE_PKCSREQ) {
                    log.debug("Received a PKCSReq message from host: " + remoteAddr);
                    // Decrypt the Scep message and extract the pkcs10 request
                    if (reqmsg.requireKeyInfo()) {
                        // scep encrypts message with the RAs certificate
                        reqmsg.setKeyInfo(racert, rapriv, cryptProvider);
                    }
                    // Verify the request
                    if (reqmsg.verify() == false) {
                        String msg = "POPO verification failed.";
                        log.error(msg);
                        throw new SignRequestSignatureException(msg);
                    }
                    String username = reqmsg.getUsername();
                    if (username == null) {
                        String msg = "No username in request, request DN: " + reqmsg.getRequestDN();
                        log.error(msg);
                        throw new SignRequestException(msg);
                    }
                    log.info("Received a SCEP/PKCS10 request for user: " + username + ", from host: "
                            + remoteAddr);
                    String authPwd = ExtraConfiguration.instance().getString(ExtraConfiguration.SCEPAUTHPWD);
                    if (StringUtils.isNotEmpty(authPwd) && !StringUtils.equals(authPwd, "none")) {
                        log.debug("Requiring authPwd in order to precess SCEP requests");
                        String pwd = reqmsg.getPassword();
                        if (!StringUtils.equals(authPwd, pwd)) {
                            log.error("Wrong auth password received in SCEP request: " + pwd);
                            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Auth pwd missmatch");
                            return;
                        }
                        log.debug("Request passed authPwd test.");
                    } else {
                        log.debug("Not requiring authPwd in order to precess SCEP requests");
                    }
                    // Try to find the CA name from the issuerDN, if we can't find it (i.e. not defined in web.xml) we use the default
                    String issuerDN = CertTools.stringToBCDNString(reqmsg.getIssuerDN());
                    String caName = ExtraConfiguration.instance().getString(issuerDN);
                    if (StringUtils.isEmpty(caName)) {
                        caName = ExtraConfiguration.instance().getString(ExtraConfiguration.SCEPDEFAULTCA);
                        log.info("Did not find a CA name from issuerDN: " + issuerDN
                                + ", using the default CA '" + caName + "'");
                    } else {
                        log.debug("Found a CA name '" + caName + "' from issuerDN: " + issuerDN);
                    }
                    // Get altNames if we can find them
                    String altNames = reqmsg.getRequestAltNames();

                    byte[] encoded = reqmsg.getCertificationRequest().getEncoded();
                    String pkcs10 = new String(Base64.encode(encoded, false));

                    // Create a pkcs10 request
                    String certificateProfile = ExtraConfiguration.instance()
                            .getString(ExtraConfiguration.SCEPCERTPROFILEKEY);
                    String entityProfile = ExtraConfiguration.instance()
                            .getString(ExtraConfiguration.SCEPENTITYPROFILEKEY);
                    boolean createOrEditUser = ExtraConfiguration.instance()
                            .getBoolean(ExtraConfiguration.SCEPEDITUSER);
                    PKCS10Request req = new PKCS10Request(100, username, reqmsg.getRequestDN(), altNames, null,
                            null, entityProfile, certificateProfile, caName, pkcs10);
                    req.setCreateOrEditUser(createOrEditUser);
                    SubMessages submessages = new SubMessages();
                    submessages.addSubMessage(req);
                    msgHome.create(transId, submessages);
                    reply = createPendingResponseMessage(reqmsg, racert, rapriv, cryptProvider)
                            .getResponseMessage();
                }
            }

            if (reply == null) {
                // This is probably a getCert message?
                log.debug("Sending HttpServletResponse.SC_NOT_IMPLEMENTED (501) response");
                response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "Can not handle request");
                return;
            }
            // Send back SCEP response, PKCS#7 which contains the end entity's certificate, or pending, or failure
            sendBinaryBytes(reply, response, "application/x-pki-message", null);
        } else if (operation.equals("GetCACert")) {
            // The response has the content type tagged as application/x-x509-ca-cert. 
            // The body of the response is a DER encoded binary X.509 certificate. 
            // For example: "Content-Type:application/x-x509-ca-cert\n\n"<BER-encoded X509>
            // IF we are not an RA, which in case we should return the same thing as GetCACertChain
            log.info("Got SCEP cert request for CA '" + message + "'");
            if (chain != null) {
                if (chain.length > 1) {
                    // We are an RA, so return the same as GetCACertChain, but with other content type
                    getCACertChain(message, remoteAddr, response, alias, raks, false);
                } else {
                    // The CA certificate is no 0
                    X509Certificate cert = (X509Certificate) chain[0];
                    if (chain.length > 1) {
                        cert = (X509Certificate) chain[1];
                    }
                    log.debug("Found cert with DN '" + cert.getSubjectDN().toString() + "'");
                    log.info("Sent certificate for CA '" + message + "' to SCEP client with ip " + remoteAddr);
                    sendBinaryBytes(cert.getEncoded(), response, "application/x-x509-ca-cert", null);
                }
            } else {
                log.error("No CA certificates found");
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "No CA certificates found.");
            }
        } else if (operation.equals("GetCACertChain")) {
            // The response for GetCACertChain is a certificates-only PKCS#7 
            // SignedDatato carry the certificates to the end entity, with a 
            // Content-Type of application/x-x509-ca-ra-cert-chain.
            log.info("Got SCEP cert chain request for CA '" + message + "'");
            getCACertChain(message, remoteAddr, response, alias, raks, true);
        } else if (operation.equals("GetCACaps")) {
            // The response for GetCACaps is a <lf> separated list of capabilities

            /*
             "GetNextCACert"       CA Supports the GetNextCACert message.
             "POSTPKIOperation"    PKIOPeration messages may be sent via HTTP POST.
             "SHA-1"               CA Supports the SHA-1 hashing algorithm in 
                               signatures and fingerprints.  If present, the
                               client SHOULD use SHA-1.  If absent, the client
                               MUST use MD5 to maintain backward compatability.
             "Renewal"             Clients may use current certificate and key to
                               authenticate an enrollment request for a new
                               certificate.  
             */
            log.info("Got SCEP CACaps request for CA '" + message + "'");
            response.setContentType("text/plain");
            response.getOutputStream().print("POSTPKIOperation\nSHA-1");
        }
    } catch (java.lang.ArrayIndexOutOfBoundsException ae) {
        log.error("Empty or invalid request received.", ae);
        // TODO: Send back proper Failure Response
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, ae.getMessage());
    } catch (Exception e) {
        log.error("Error in ScepRAServlet:", e);
        // TODO: Send back proper Failure Response
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    }
}

From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java

/**
 *  ?  ?  ? ?  ?  ? ??? //  w w  w.jav  a 2  s .  c  om
 *  . ?  ?  ?   ?      ?  post-?
 *   ??    ?  ? ? SSL- ?
 *  ? ? ?   ?. 
 * ? ??   ? ?  ?   ? post-? ? . 
 * @param signers
 * @param clientCerts
 * @return
 * @throws CertStoreException 
 */
private boolean isBadBinOrIin(SignerInformationStore signers, CertStore clientCerts) throws CertStoreException {
    if (signers.getSigners().size() == 0) {
        verifyErrorMsg = "    ?.";
        return true;
    }
    Iterator it = signers.getSigners().iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        X509CertSelector signerConstraints = signer.getSID();
        Collection certCollection = clientCerts.getCertificates(signerConstraints);
        Iterator certIt = certCollection.iterator();
        //System.out.println(  );
        if (certCollection.size() == 0) {
            verifyErrorMsg = "    ?  ? .";
            return true;
        }
        while (certIt.hasNext()) {
            X509Certificate cert = (X509Certificate) certIt.next();
            String subj = cert.getSubjectDN().getName();
            Pattern pt;
            Matcher m;
            if (typeOfRespondent.equals(TypeOfRespondent.FIRM)) {
                pt = Pattern.compile("BIN(\\d{12})");
                m = pt.matcher(subj); // get a matcher object
                if (m.find()) {
                    if (realBinIin.equals(m.group(1))) {
                        return false;
                    } else {
                        verifyErrorMsg = "? ??   ? ? ? ? '"
                                + realBinIin + "' ,   c ? '" + m.group(1) + "'. ";
                    }
                } else {
                    verifyErrorMsg = " ? c    ? '"
                            + realBinIin + "' .";
                }
            } else {
                pt = Pattern.compile("IIN(\\d{12})");
                m = pt.matcher(subj); // get a matcher object
                if (m.find()) {
                    if (realBinIin.equals(m.group(1))) {
                        return false;
                    } else {
                        verifyErrorMsg = "? ??   ? ? ? ? '"
                                + realBinIin + "' ,   c ? '" + m.group(1) + "'. ";
                    }
                } else {
                    verifyErrorMsg = " ? c    ? '"
                            + realBinIin + "' .";
                }
            }
        }
    }
    return true;
}

From source file:org.ejbca.extra.ra.ScepRAServlet.java

private ScepResponseMessage createPendingResponseMessage(IRequestMessage req, X509Certificate racert,
        PrivateKey rakey, String cryptProvider) throws InvalidKeyException, NoSuchAlgorithmException,
        NoSuchProviderException, IOException, SignRequestException, NotFoundException {
    ScepResponseMessage ret = new ScepResponseMessage();
    // Create the response message and set all required fields
    if (ret.requireSignKeyInfo()) {
        log.debug("Signing message with cert: " + racert.getSubjectDN().getName());
        ret.setSignKeyInfo(racert, rakey, cryptProvider);
    }// w  w w .j  a va  2 s.  c  o m
    if (req.getSenderNonce() != null) {
        ret.setRecipientNonce(req.getSenderNonce());
    }
    if (req.getTransactionId() != null) {
        ret.setTransactionId(req.getTransactionId());
    }
    // Sendernonce is a random number
    byte[] senderNonce = new byte[16];
    randomSource.nextBytes(senderNonce);
    ret.setSenderNonce(new String(Base64.encode(senderNonce)));
    // If we have a specified request key info, use it in the reply
    if (req.getRequestKeyInfo() != null) {
        ret.setRecipientKeyInfo(req.getRequestKeyInfo());
    }
    // Which digest algorithm to use to create the response, if applicable
    ret.setPreferredDigestAlg(req.getPreferredDigestAlg());
    // Include the CA cert or not in the response, if applicable for the response type
    ret.setIncludeCACert(req.includeCACert());
    ret.setStatus(ResponseStatus.PENDING);
    ret.create();
    return ret;
}

From source file:com.vmware.identity.openidconnect.client.OIDCClient.java

/**
 * tokens by smart card certificate that represents a PersonUser
 *
 * @param personUserCertificate     smart card cert
 * @param signer                    client-implemented interface that signs an object with the smart card private key
 * @param tokenSpec                 Specification of tokens requested.
 *///w  ww.ja va 2 s .c  o m
public OIDCTokens acquireTokensByPersonUserCertificate(X509Certificate personUserCertificate,
        PersonUserAssertionSigner signer, TokenSpec tokenSpec)
        throws OIDCClientException, OIDCServerException, TokenValidationException, SSLConnectionException {
    Validate.notNull(personUserCertificate, "personUserCertificate");
    Validate.notNull(signer, "signer");
    Validate.notNull(tokenSpec, "tokenSpec");

    Date issueTime = new Date(); // now
    URI tokenEndpointURI = getTokenEndpointURI();

    PersonUserAssertion personUserAssertion;
    try {
        personUserAssertion = new PersonUserAssertion(signer, new JWTID(),
                personUserCertificate.getSubjectDN().getName(), tokenEndpointURI, issueTime);
    } catch (JOSEException e) {
        throw new OIDCClientException("failed to construct PersonUserAssertion", e);
    }

    return acquireTokens(new PersonUserCertificateGrant(personUserCertificate, personUserAssertion), tokenSpec);
}

From source file:org.tolven.config.model.CredentialManager.java

private X509Certificate[] getX509CertificateChain(CertificateGroupDetail certGroup) {
    List<X509Certificate> certificates = new ArrayList<X509Certificate>();
    X509Certificate certificate = getTolvenConfigWrapper().getX509Certificate(certGroup);
    certificates.add(certificate);//w  w w  . j a va  2s  .  c  om
    if (!certificate.getIssuerDN().equals(certificate.getSubjectDN())) {
        X509Certificate issuingCertificate = null;
        do {
            CertificateGroupDetail issuingCertGroup = getTolvenConfigWrapper()
                    .getCredentialGroup(certGroup.getCertificate().getCaRefId());
            issuingCertificate = getTolvenConfigWrapper().getX509Certificate(issuingCertGroup);
            if (!certificates.contains(issuingCertificate))
                certificates.add(issuingCertificate);

        } while ((!issuingCertificate.getIssuerDN().equals(issuingCertificate.getSubjectDN())));
    }
    X509Certificate[] certArr = new X509Certificate[certificates.size()];
    for (int i = 0; i < certificates.size(); i++)
        certArr[i] = certificates.get(i);
    return certArr;
}

From source file:org.syncany.plugins.webdav.WebdavTransferManager.java

private String formatCertificate(X509Certificate cert) {
    try {/*from  ww  w .jav a 2 s .  com*/
        CipherUtil.enableUnlimitedStrength(); // Dirty!

        String checksumMd5 = formatChecksum(createChecksum(cert.getEncoded(), "MD5"));
        String checksumSha1 = formatChecksum(createChecksum(cert.getEncoded(), "SHA1"));
        String checksumSha256 = formatChecksum(createChecksum(cert.getEncoded(), "SHA256"));

        StringBuilder sb = new StringBuilder();

        sb.append(String.format("Owner: %s\n", cert.getSubjectDN().getName()));
        sb.append(String.format("Issuer: %s\n", cert.getIssuerDN().getName()));
        sb.append(String.format("Serial number: %d\n", cert.getSerialNumber()));
        sb.append(String.format("Valid from %s until: %s\n", cert.getNotBefore().toString(),
                cert.getNotAfter().toString()));
        sb.append("Certificate fingerprints:\n");
        sb.append(String.format(" MD5:  %s\n", checksumMd5));
        sb.append(String.format(" SHA1: %s\n", checksumSha1));
        sb.append(String.format(" SHA256: %s", checksumSha256));

        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.otterca.persistence.dao.X509CertificateDaoDatastore.java

/**
 * @see com.otterca.persistence.dao.X509CertificateDao#put(java.security.cert
 *      .X509Certificate)/*from   w  w  w. java2s .c  o  m*/
 */
public void put(X509Certificate cert) throws IOException, CertificateEncodingException {

    // TODO: we want cert's issuer to be its parent. For now certs don't
    // have parents.
    Key key = generateKey(cert);
    Entity e = new Entity(key);

    // also set parent...

    e.setProperty(CERTIFICATE, new Blob(cert.getEncoded()));
    // up to 20 octets - 40 characters
    e.setProperty(SERIAL_NUMBER, cert.getSerialNumber().toString(16));
    // up to 500 unicode characters
    e.setProperty(SUBJECT_DN, cert.getSubjectDN().getName());
    // up to 500 unicode characters
    e.setProperty(ISSUER_DN, cert.getIssuerDN().getName());
    e.setProperty(NOT_BEFORE, cert.getNotBefore());
    e.setProperty(NOT_AFTER, cert.getNotAfter());

    // RFC search criteria
    e.setProperty(COMMON_NAME, x509CertUtil.getName(cert));
    e.setProperty(FINGERPRINT, x509CertUtil.getFingerprint(cert));
    e.setProperty(CERT_HASH, x509CertUtil.getCertificateHash(cert));
    e.setProperty(ISSUER_HASH, x509CertUtil.getIHash(cert));
    e.setProperty(SUBJECT_HASH, x509CertUtil.getSHash(cert));
    // e.setProperty(AKID_HASH, x509CertUtil.getAkidHash(cert));
    e.setProperty(SKID_HASH, x509CertUtil.getSkidHash(cert));
    // e.setProperty(IANDS_HASH, x509CertUtil.getIandSHash(cert));

    // e.setProperty(EMAIL) ?...

    e.setUnindexedProperty(TRUSTED, false);
    e.setUnindexedProperty(STATUS, UNKNOWN);

    datastore.put(e);
}