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:org.ejbca.core.protocol.ocsp.extension.unid.OCSPUnidExtension.java

@Override
public Map<ASN1ObjectIdentifier, Extension> process(X509Certificate[] requestCertificates, String remoteAddress,
        String remoteHost, X509Certificate cert, CertificateStatus status) {
    if (m_log.isTraceEnabled()) {
        m_log.trace(">process()");
    }/*from  ww w.jav  a  2 s . c om*/
    // Check authorization first
    if (!checkAuthorization(requestCertificates, remoteAddress, remoteHost)) {
        errCode = OCSPUnidExtension.ERROR_UNAUTHORIZED;
        return null;
    }
    // If the certificate is revoked, we must not return an FNR
    if (status != null) {
        errCode = OCSPUnidExtension.ERROR_CERT_REVOKED;
        return null;
    }
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet result = null;
    String fnr = null;
    String sn = null;
    try {
        // The Unis is in the DN component serialNumber
        sn = CertTools.getPartFromDN(cert.getSubjectDN().getName(), "SN");
        if (sn != null) {
            if (m_log.isDebugEnabled()) {
                m_log.debug("Found serialNumber: " + sn);
            }
            String iMsg = intres.getLocalizedMessage("ocsp.receivedunidreq", remoteAddress, remoteHost, sn);
            m_log.info(iMsg);
            try {
                con = ServiceLocator.getInstance().getDataSource(dataSourceJndi).getConnection();
            } catch (SQLException e) {
                String errMsg = intres.getLocalizedMessage("ocsp.errordatabaseunid");
                m_log.error(errMsg, e);
                errCode = OCSPUnidExtension.ERROR_SERVICE_UNAVAILABLE;
                return null;
            }
            ps = con.prepareStatement("select fnr from UnidFnrMapping where unid=?");
            ps.setString(1, sn);
            result = ps.executeQuery();
            if (result.next()) {
                fnr = result.getString(1);
            }
        } else {
            String errMsg = intres.getLocalizedMessage("ocsp.errorunidnosnindn", cert.getSubjectDN().getName());
            m_log.error(errMsg);
            errCode = OCSPUnidExtension.ERROR_NO_SERIAL_IN_DN;
            return null;
        }
        m_log.trace("<process()");
    } catch (Exception e) {
        throw new EJBException(e);
    } finally {
        JDBCUtil.close(con, ps, result);
    }

    // Construct the response extentsion if we found a mapping
    if (fnr == null) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorunidnosnmapping", sn);
        m_log.error(errMsg);
        errCode = OCSPUnidExtension.ERROR_NO_FNR_MAPPING;
        return null;

    }
    String errMsg = intres.getLocalizedMessage("ocsp.returnedunidresponse", remoteAddress, remoteHost, fnr, sn);
    m_log.info(errMsg);
    FnrFromUnidExtension ext = new FnrFromUnidExtension(fnr);
    HashMap<ASN1ObjectIdentifier, Extension> ret = new HashMap<ASN1ObjectIdentifier, Extension>();
    try {
        ret.put(FnrFromUnidExtension.FnrFromUnidOid,
                new Extension(FnrFromUnidExtension.FnrFromUnidOid, false, new DEROctetString(ext)));
    } catch (IOException e) {
        throw new IllegalStateException("Unexpected IOException caught.", e);
    }
    return ret;
}

From source file:eu.peppol.outbound.transmission.As2MessageSender.java

/**
 * Handles the HTTP 200 POST response (the MDN with status indications)
 *
 * @param transmissionId the transmissionId (used in HTTP headers as Message-ID)
 * @param outboundMic    the calculated mic of the payload (should be verified against the one returned in MDN)
 * @param postResponse   the http response to be decoded as MDN
 * @return// ww w. j  a  v a  2s.c o  m
 */
MimeMessage handleTheHttpResponse(TransmissionId transmissionId, Mic outboundMic,
        CloseableHttpResponse postResponse, SmpLookupManager.PeppolEndpointData peppolEndpointData) {

    try {

        HttpEntity entity = postResponse.getEntity(); // Any textual results?
        if (entity == null) {
            throw new IllegalStateException(
                    "No contents in HTTP response with rc=" + postResponse.getStatusLine().getStatusCode());
        }

        String contents = EntityUtils.toString(entity);

        if (traceEnabled) {
            log.debug("HTTP-headers:");
            Header[] allHeaders = postResponse.getAllHeaders();
            for (Header header : allHeaders) {
                log.debug("" + header.getName() + ": " + header.getValue());
            }
            log.debug("Contents:\n" + contents);
            log.debug("---------------------------");
        }

        Header contentTypeHeader = postResponse.getFirstHeader("Content-Type");
        if (contentTypeHeader == null) {
            throw new IllegalStateException("No Content-Type header in response, probably a server error");
        }
        String contentType = contentTypeHeader.getValue();

        MimeMessage mimeMessage = null;
        try {
            mimeMessage = MimeMessageHelper.parseMultipart(contents, new MimeType(contentType));

            try {
                mimeMessage.writeTo(System.out);
            } catch (MessagingException e) {
                throw new IllegalStateException("Unable to print mime message");
            }

        } catch (MimeTypeParseException e) {
            throw new IllegalStateException("Invalid Content-Type header");
        }

        // verify the signature of the MDN, we warn about dodgy signatures
        try {
            SignedMimeMessage signedMimeMessage = new SignedMimeMessage(mimeMessage);
            X509Certificate cert = signedMimeMessage.getSignersX509Certificate();
            cert.checkValidity();

            // Verify if the certificate used by the receiving Access Point in
            // the response message does not match its certificate published by the SMP
            if (peppolEndpointData.getCommonName() == null || !CommonName
                    .valueOf(cert.getSubjectX500Principal()).equals(peppolEndpointData.getCommonName())) {
                throw new CertificateException(
                        "Common name in certificate from SMP does not match common name in AP certificate");
            }

            log.debug("MDN signature was verfied for : " + cert.getSubjectDN().toString());
        } catch (Exception ex) {
            log.warn("Exception when verifying MDN signature : " + ex.getMessage());
        }

        // Verifies the actual MDN
        MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
        String msg = mdnMimeMessageInspector.getPlainTextPartAsText();

        if (mdnMimeMessageInspector.isOkOrWarning(outboundMic)) {

            return mimeMessage;
        } else {
            log.error("AS2 transmission failed with some error message, msg :" + msg);
            log.error(contents);
            throw new IllegalStateException("AS2 transmission failed : " + msg);
        }

    } catch (IOException e) {
        throw new IllegalStateException("Unable to obtain the contents of the response: " + e.getMessage(), e);
    } finally {
        try {
            postResponse.close();
        } catch (IOException e) {
            throw new IllegalStateException("Unable to close http connection: " + e.getMessage(), e);
        }
    }

}

From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java

/**
 * Test conversion to byte array and back.
 *///from   ww w.  ja v  a  2s  .co m
@Test
public void testTestRoundtrip() throws GeneralSecurityException {
    populate(builder);
    X509Certificate expected = builder.build(keyPair.getPrivate());

    X509Certificate actual = certUtil.getCertificate(expected.getEncoded());
    assertEquals(actual.getSerialNumber(), expected.getSerialNumber());
    assertEquals(actual.getIssuerDN().toString(), expected.getIssuerDN().toString());
    assertEquals(actual.getSubjectDN().toString(), expected.getSubjectDN().toString());
    assertEquals(actual.getNotBefore(), expected.getNotBefore());
    assertEquals(actual.getNotAfter(), expected.getNotAfter());
}

From source file:de.duenndns.ssl.MemorizingTrustManager.java

private String hostNameMessage(X509Certificate cert, String hostname) {
    StringBuffer si = new StringBuffer();

    si.append(master.getString(R.string.mtm_hostname_mismatch, hostname));
    si.append("\n\n");
    try {// ww  w.j  a va 2s.  c om
        Collection<List<?>> sans = cert.getSubjectAlternativeNames();
        if (sans == null) {
            si.append(cert.getSubjectDN());
            si.append("\n");
        } else
            for (List<?> altName : sans) {
                Object name = altName.get(1);
                if (name instanceof String) {
                    si.append("[");
                    si.append((Integer) altName.get(0));
                    si.append("] ");
                    si.append(name);
                    si.append("\n");
                }
            }
    } catch (CertificateParsingException e) {
        e.printStackTrace();
        si.append("<Parsing error: ");
        si.append(e.getLocalizedMessage());
        si.append(">\n");
    }
    si.append("\n");
    si.append(master.getString(R.string.mtm_connect_anyway));
    si.append("\n\n");
    si.append(master.getString(R.string.mtm_cert_details));
    certDetails(si, cert);
    return si.toString();
}

From source file:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java

/**
 * Revocation check function 1. use ocsp first if it is enabled 2. fail if
 * the cert is revoked 3. Fall back to CRL if ocsp fails for reason other
 * then revoked 4. CRL validation using provided URL and in-cert URL
 *
 * Note:OCSP nonce extension appears not currently controllable in Java's
 * default OCSPChecker.//from w  ww.j  a  v  a 2  s .c  o m
 *
 * @param certs
 *            Client cert chain. It could be a leaf certificate, a partial or a
 *            full chain including root CA.
 * Current implementation only relies on leaf certificate and use it to build certificate path then validate it.
 * @param authStatExt
 *            AuthStat extensions for profiling the detailed steps.
 * @throws CertificateRevocationCheckException unable to validate revocation status.
 * @throws IdmCertificateRevokedException  certificate revoked
 * @throws InvalidArgumentException
 * @throws CertificatePathBuildingException  cert path building error of any reasons: such as expired cert, etc.
 */
public void validate(X509Certificate cert, Map<String, String> authStatExt)
        throws CertificateRevocationCheckException, IdmCertificateRevokedException, InvalidArgumentException,
        CertificatePathBuildingException {

    if (null == cert) {
        throw new InvalidArgumentException("No certs to validate.");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Certificate policy: " + this.certPolicy.toString());
        logger.debug("Checking revocation for certificate: " + cert.getSubjectDN());
    }

    // Build the certpath
    long startTime = System.nanoTime();

    CertPath certPath = buildCertPath(cert);

    authStatExt.put("buildCertPath",
            String.format("%d Ms", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)));
    startTime = System.nanoTime();

    // Validate certpath
    validateCertPath(certPath);
    authStatExt.put("validateCertPath",
            String.format("%d Ms", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)));
    logger.info("Successfully validated client certificate : " + cert.getSubjectDN());

}

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

/**
 *
 * returns the public key of the signing certificate used for a signed
 * JAXB object.//from w  w  w  . j av  a2 s  .c o m
 *
 * @param obj
 * @return null if the item is not signed or if it references a
 * certificate that is not present in the current keystore
 * * @throws IllegalArgumentException for null input
 */
private X509Certificate getSigningCertificatePublicKey(Element docElement)
        throws IllegalArgumentException, CertificateException {
    if (docElement == null) {
        throw new IllegalArgumentException();
    }

    NodeList childNodes = docElement.getChildNodes(); //children, one of these SHOULD be our signature element
    // X509Certificate signingcert = null;
    for (int i = 0; i < childNodes.getLength(); i++) {
        //System.out.println(childNodes.item(i).getNamespaceURI() + " " + childNodes.item(i).getNodeName());
        if (childNodes.item(i).getNamespaceURI().equalsIgnoreCase(XML_DIGSIG_NS)
                && childNodes.item(i).getLocalName().equalsIgnoreCase("Signature")) {
            Node sig = childNodes.item(i);
            for (int k = 0; k < sig.getChildNodes().getLength(); k++) {
                //      System.out.println(sig.getChildNodes().item(k).getNamespaceURI() + " " + sig.getChildNodes().item(k).getNodeName());
                if (sig.getChildNodes().item(k).getLocalName().equalsIgnoreCase("KeyInfo")) {
                    //TODO figure out how to reference Subject DN, serial, thumbprint, etc
                    for (int j = 0; j < sig.getChildNodes().item(k).getChildNodes().getLength(); j++) {
                        if (sig.getChildNodes().item(k).getChildNodes().item(j).getLocalName()
                                .equalsIgnoreCase("X509Data")) {
                            Node X509Data = sig.getChildNodes().item(k).getChildNodes().item(j);
                            for (int x = 0; x < X509Data.getChildNodes().getLength(); x++) {
                                if (X509Data.getChildNodes().item(x).getLocalName()
                                        .equalsIgnoreCase("X509Certificate")) {
                                    //yay found it!

                                    String c = "-----BEGIN CERTIFICATE-----\n"
                                            + X509Data.getChildNodes().item(x).getTextContent()
                                            + "\n-----END CERTIFICATE-----";
                                    //System.out.println("X509 Public key: " + c);
                                    InputStream is = new ByteArrayInputStream(c.getBytes());
                                    X509Certificate cert = (X509Certificate) cf.generateCertificate(is);

                                    logger.info("embedded certificate found, X509 public key "
                                            + cert.getSubjectDN().toString());
                                    return cert;

                                }

                                //if we have a 
                                //TODO other parsing items, lots of other potentials here
                            }
                            X509Certificate cert = FindCert(X509Data.getChildNodes());
                            if (cert != null) {
                                logger.info("certificate loaded from local trust store, X509 public key "
                                        + cert.getSubjectDN().toString());
                                return cert;
                            }
                        }

                    }
                    break;
                }

            }

            break;
        }
    }
    return null;
}

From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java

/**
 * Test builder with issuer certificate.
 * /*  w  ww . j  a v  a2 s . c  om*/
 * @throws Exception
 */
@Test
public void testBuilderCertWithValidIssuer() throws GeneralSecurityException {
    // create issuer certificate
    populate(builder);
    builder.setSubject(ISSUER_NAME);
    builder.setIssuer(ISSUER_NAME);
    builder.setPublicKey(issuerKeyPair.getPublic());
    builder.setBasicConstraints(true);

    X509Certificate issuer = builder.build(issuerKeyPair.getPrivate());

    // perform basic validation.
    issuer.verify(issuerKeyPair.getPublic());

    // verify the basics
    assertEquals(issuer.getSerialNumber(), serial);
    assertEquals(issuer.getSubjectDN().getName(), ISSUER_NAME);
    assertEquals(issuer.getIssuerDN().getName(), ISSUER_NAME);
    assertEquals(issuer.getNotBefore(), notBefore.getTime());
    assertEquals(issuer.getNotAfter(), notAfter.getTime());
    // assertEquals(issuer.getPublicKey(), issuerKeyPair.getPublic());
    // FIXME: returns null

    builder.reset();

    // create subject certificate
    populate(builder);
    builder.setIssuer(issuer);

    X509Certificate cert = builder.build(keyPair.getPrivate());

    // perform basic validation.
    cert.verify(keyPair.getPublic());

    // verify the basics
    assertEquals(cert.getSerialNumber(), serial);
    assertEquals(cert.getSubjectDN().getName(), SUBJECT_NAME);
    assertEquals(cert.getIssuerDN().getName(), ISSUER_NAME);
    assertEquals(cert.getNotBefore(), notBefore.getTime());
    assertEquals(cert.getNotAfter(), notAfter.getTime());
    // assertEquals(cert.getPublicKey(), keyPair.getPublic()); FIXME:
    // returns null
}

From source file:org.yawlfoundation.yawl.digitalSignature.DigitalSignature.java

public boolean checkSignature(byte[] Document) {
    try {//ww  w  .ja  v a  2  s.  com
        System.out.println("Beginning of Checking XmlSignature:");
        System.out.println(Document);

        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        // extract the Signed Fingerprint data
        CMSSignedData signature = new CMSSignedData(Document);
        System.out.println("Beginning of Checking XmlSignature:");

        SignerInformation signer = (SignerInformation) signature.getSignerInfos().getSigners().iterator()
                .next();
        System.out.println("Beginning of Checking XmlSignature:");

        // Get from the collection the appropriate registered certificate
        CertStore cs = signature.getCertificatesAndCRLs("Collection", "BC");
        Iterator iter = cs.getCertificates(signer.getSID()).iterator();
        System.out.println("Beginning of Checking XmlSignature:");
        X509Certificate certificate = (X509Certificate) iter.next();
        System.out.println("Beginning of Checking XmlSignature:");
        // get the contents of the document
        CMSProcessable sg = signature.getSignedContent();
        byte[] data = (byte[]) sg.getContent();
        String content = new String(data);

        //convert the document content to a valid xml document for YAWL
        org.w3c.dom.Document XMLNode = ConvertStringToDocument(content);
        org.jdom2.input.DOMBuilder builder = new org.jdom2.input.DOMBuilder();
        Doc = builder.build(XMLNode);

        //Check the document
        System.out.println("xml to Sign:");
        System.out.println(JDOMUtil.documentToString(Doc));

        // get the name of the signer
        _Name = certificate.getSubjectDN().getName().split("(=|, )", -1).toString();
        //return the result of the signature checking
        return signer.verify(certificate, "BC");

    } catch (Exception e) {
        System.out.println("Test error");
        e.printStackTrace();
        return false;
    }

}

From source file:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java

@Test
public void test08ScepGetCACert() throws Exception {
    {// ww w  .  j  a va 2s.  co m
        String reqUrl = httpReqPath + '/' + resourceScep + "?operation=GetCACert&message="
                + URLEncoder.encode(x509ca.getName(), "UTF-8");
        URL url = new URL(reqUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.getDoOutput();
        con.connect();
        assertEquals("Response code is not 200 (OK)", 200, con.getResponseCode());
        // Some appserver (Weblogic) responds with
        // "application/x-x509-ca-cert; charset=UTF-8"
        assertTrue(con.getContentType().startsWith("application/x-x509-ca-cert"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // This works for small requests, and SCEP requests are small enough
        InputStream in = con.getInputStream();
        int b = in.read();
        while (b != -1) {
            baos.write(b);
            b = in.read();
        }
        baos.flush();
        in.close();
        byte[] respBytes = baos.toByteArray();
        assertNotNull("Response can not be null.", respBytes);
        assertTrue(respBytes.length > 0);
        X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(respBytes);
        // Check that we got the right cert back
        assertEquals(cacert.getSubjectDN().getName(), cert.getSubjectDN().getName());
    }

    // 
    // Test the same message but without message component, it should use a default CA
    {
        // Try with a non extisting CA first, should respond with a 404
        updatePropertyOnServer("scep.defaultca", "NonExistingCAForSCEPTest");
        String reqUrl = httpReqPath + '/' + resourceScep + "?operation=GetCACert";
        URL url = new URL(reqUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.getDoOutput();
        con.connect();
        assertEquals("Response code is not 404 (not found)", 404, con.getResponseCode());
        // Try with the good CA            
        updatePropertyOnServer("scep.defaultca", x509ca.getName());
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.getDoOutput();
        con.connect();
        assertEquals("Response code is not 200 (OK)", 200, con.getResponseCode());
        // Some appserver (Weblogic) responds with
        // "application/x-x509-ca-cert; charset=UTF-8"
        assertTrue(con.getContentType().startsWith("application/x-x509-ca-cert"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // This works for small requests, and SCEP requests are small enough
        InputStream in = con.getInputStream();
        int b = in.read();
        while (b != -1) {
            baos.write(b);
            b = in.read();
        }
        baos.flush();
        in.close();
        byte[] respBytes = baos.toByteArray();
        assertNotNull("Response can not be null.", respBytes);
        assertTrue(respBytes.length > 0);
        X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(respBytes);
        // Check that we got the right cert back
        assertEquals(cacert.getSubjectDN().getName(), cert.getSubjectDN().getName());
    }
}

From source file:org.apache.hadoop.security.ssl.TestReloadingX509KeyManager.java

@Test(timeout = 4000)
public void testReload() throws Exception {
    KeyPair keyPair = KeyStoreTestUtil.generateKeyPair(KEY_PAIR_ALGORITHM);
    X509Certificate cert1 = KeyStoreTestUtil.generateCertificate("CN=cert1", keyPair, 2, CERTIFICATE_ALGORITHM);
    String keyStoreLocation = Paths.get(BASE_DIR, "testKeystore.jks").toString();
    KeyStoreTestUtil.createKeyStore(keyStoreLocation, KEYSTORE_PASSWORD, "cert1", keyPair.getPrivate(), cert1);

    ReloadingX509KeyManager keyManager = new ReloadingX509KeyManager("jks", keyStoreLocation, KEYSTORE_PASSWORD,
            KEYSTORE_PASSWORD, 10, TimeUnit.MILLISECONDS);

    try {//w ww  . java 2 s. c  o m
        keyManager.init();

        TimeUnit reloadTimeUnit = keyManager.getReloadTimeUnit();
        long reloadInterval = keyManager.getReloadInterval();

        X509Certificate[] certChain = keyManager.getCertificateChain("cert1");
        assertNotNull("Certificate chain should not be null for alias cert1", certChain);
        assertEquals("Certificate chain should be 1", 1, certChain.length);
        assertEquals("DN for cert1 should be CN=cert1", cert1.getSubjectDN().getName(),
                certChain[0].getSubjectDN().getName());

        // Wait a bit for the modification time to be different
        reloadTimeUnit.sleep(reloadInterval);
        TimeUnit.SECONDS.sleep(1);

        // Replace keystore with a new one with a different DN
        X509Certificate cert2 = KeyStoreTestUtil.generateCertificate("CN=cert2", keyPair, 2,
                CERTIFICATE_ALGORITHM);
        KeyStoreTestUtil.createKeyStore(keyStoreLocation, KEYSTORE_PASSWORD, "cert2", keyPair.getPrivate(),
                cert2);

        reloadTimeUnit.sleep(reloadInterval * 2);

        certChain = keyManager.getCertificateChain("cert1");
        assertNull("Certificate chain for alias cert1 should be null", certChain);
        certChain = keyManager.getCertificateChain("cert2");
        assertNotNull("Certificate chain should not be null for alias cert2", certChain);
        assertEquals("Certificate chain should be 1", 1, certChain.length);
        assertEquals("DN for cert2 should be CN=cert2", cert2.getSubjectDN().getName(),
                certChain[0].getSubjectDN().getName());

    } finally {
        keyManager.stop();
    }
}