Example usage for java.security.cert X509Certificate getIssuerX500Principal

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

Introduction

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

Prototype

public X500Principal getIssuerX500Principal() 

Source Link

Document

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

Usage

From source file:com.microsoft.tfs.core.config.httpclient.internal.DefaultX509TrustManager.java

/**
 * {@inheritDoc}/*  w  w w  .j  a  v a 2 s.  co m*/
 */
@Override
public void checkServerTrusted(X509Certificate[] certificates, final String authType)
        throws CertificateException {
    if (certificates != null && certificates.length > 0) {
        /*
         * See if the terminal certificate in the chain is known to us (we
         * have its certificate.) If so, we can add our certificate to be
         * the last in the list.
         *
         * This emulates sending the certificate in the server's chain,
         * without making the server team do any actual work.
         */
        final X509Certificate terminalCertificate = certificates[certificates.length - 1];

        /*
         * Make sure the terminal certificate is not self-signed. We cannot
         * possibly have an issuer certificate to add if the terminal
         * certificate is self-signed, and we may cause problems with the
         * certificate validation.
         */
        if (!terminalCertificate.getIssuerX500Principal()
                .equals(terminalCertificate.getSubjectX500Principal())) {
            for (final X509Certificate certificateAddition : certificateAdditions) {
                /*
                 * If this certificate was issued by our known-good
                 * principal, and its issuer is not its principal (ie, it is
                 * not self-signed), then include it.
                 */
                if (terminalCertificate.getIssuerX500Principal()
                        .equals(certificateAddition.getSubjectX500Principal())) {
                    log.info(MessageFormat.format("Including certificate for {0}", //$NON-NLS-1$
                            certificateAddition.getSubjectX500Principal()));

                    /*
                     * Rewrite the certificate array to include our trusted
                     * certificate at the end of the chain.
                     */
                    final X509Certificate[] newCertificates = new X509Certificate[certificates.length + 1];

                    for (int i = 0; i < certificates.length; i++) {
                        newCertificates[i] = certificates[i];
                    }

                    newCertificates[newCertificates.length - 1] = certificateAddition;

                    certificates = newCertificates;

                    break;
                }
            }
        }
    }

    standardTrustManager.checkServerTrusted(certificates, authType);
}

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

/**
 * Harvest the CRLs for specified certificate chain if caching is set for
 * the trust domain and no cache is yet active.
 *//*from  w w w  . j  av a 2s.com*/
private void harvest(TrustDomainEntity trustDomain, List<X509Certificate> certificateChain) {

    if (trustDomain.isUseCaching()) {
        for (X509Certificate certificate : certificateChain) {
            String issuerName = certificate.getIssuerX500Principal().toString();
            LOG.debug("harvest - Don't have Issuer's Serial Number??");
            CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO
                    .findCertificateAuthority(issuerName);
            if (null != certificateAuthority && (certificateAuthority.getStatus().equals(Status.INACTIVE)
                    || certificateAuthority.getStatus().equals(Status.NONE))) {
                if (null != certificateAuthority.getCrlUrl()) {
                    certificateAuthority.setStatus(Status.PROCESSING);
                    try {
                        this.notificationService.notifyDownloader(certificateAuthority.getName(), false);
                        if (null != certificateAuthority.getTrustPoint()
                                && null == certificateAuthority.getTrustPoint().getFireDate()) {
                            this.schedulingService.startTimer(certificateAuthority.getTrustPoint());
                        }
                    } catch (JMSException e) {
                        this.auditDAO.logAudit("Failed to notify harvester: " + e.getMessage());
                        LOG.error(e.getMessage(), e);
                    } catch (InvalidCronExpressionException e) {
                        this.auditDAO.logAudit("Failed to start timer for trust point: "
                                + certificateAuthority.getTrustPoint().getName());
                        LOG.error(e.getMessage(), e);
                    }
                } else {
                    certificateAuthority.setStatus(Status.NONE);
                }
            }
        }
    }
}

From source file:be.fedict.eid.applet.service.signer.facets.XAdESSignatureFacet.java

/**
 * Gives back the JAXB CertID data structure.
 * /*from  w w w  .  java  2  s .  com*/
 * @param certificate
 * @param xadesObjectFactory
 * @param xmldsigObjectFactory
 * @param digestAlgorithm
 * @return
 */
public static CertIDType getCertID(X509Certificate certificate, ObjectFactory xadesObjectFactory,
        be.fedict.eid.applet.service.signer.jaxb.xmldsig.ObjectFactory xmldsigObjectFactory,
        DigestAlgo digestAlgorithm, boolean issuerNameNoReverseOrder) {
    CertIDType certId = xadesObjectFactory.createCertIDType();

    X509IssuerSerialType issuerSerial = xmldsigObjectFactory.createX509IssuerSerialType();
    certId.setIssuerSerial(issuerSerial);
    String issuerName;
    if (issuerNameNoReverseOrder) {
        try {
            /*
             * Make sure the DN is encoded using the same order as present
             * within the certificate. This is an Office2010 work-around.
             * Should be reverted back.
             * 
             * XXX: not correct according to RFC 4514.
             */
            issuerName = PrincipalUtil.getIssuerX509Principal(certificate).getName().replace(",", ", ");
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("cert encoding error: " + e.getMessage(), e);
        }
    } else {
        issuerName = certificate.getIssuerX500Principal().toString();
    }
    issuerSerial.setX509IssuerName(issuerName);
    issuerSerial.setX509SerialNumber(certificate.getSerialNumber());

    byte[] encodedCertificate;
    try {
        encodedCertificate = certificate.getEncoded();
    } catch (CertificateEncodingException e) {
        throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
    }
    DigestAlgAndValueType certDigest = getDigestAlgAndValue(encodedCertificate, xadesObjectFactory,
            xmldsigObjectFactory, digestAlgorithm);
    certId.setCertDigest(certDigest);

    return certId;
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileC.java

/**
 * Gives back the JAXB CertID data structure.
 * //from   w w w  . j  av a  2s .c o  m
 * @param certificate
 * @param xadesObjectFactory
 * @param xmldsigObjectFactory
 * @param digestAlgorithm
 * @return
 */
private CertIDType getCertID(X509Certificate certificate, DigestAlgorithm digestAlgorithm) {
    CertIDType certId = xadesObjectFactory.createCertIDType();

    X509IssuerSerialType issuerSerial = getXmldsigObjectFactory().createX509IssuerSerialType();
    certId.setIssuerSerial(issuerSerial);
    String issuerName = certificate.getIssuerX500Principal().toString();
    issuerSerial.setX509IssuerName(issuerName);
    issuerSerial.setX509SerialNumber(certificate.getSerialNumber());

    byte[] encodedCertificate;
    try {
        encodedCertificate = certificate.getEncoded();
    } catch (CertificateEncodingException e) {
        throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
    }
    DigestAlgAndValueType certDigest = getDigestAlgAndValue(encodedCertificate, digestAlgorithm);
    certId.setCertDigest(certDigest);

    return certId;
}

From source file:org.apache.nifi.toolkit.tls.util.TlsHelperTest.java

@Test
public void testIssueCert() throws IOException, CertificateException, NoSuchAlgorithmException,
        OperatorCreationException, NoSuchProviderException, InvalidKeyException, SignatureException {
    X509Certificate issuer = loadCertificate(
            new InputStreamReader(getClass().getClassLoader().getResourceAsStream("rootCert.crt")));
    KeyPair issuerKeyPair = loadKeyPair(
            new InputStreamReader(getClass().getClassLoader().getResourceAsStream("rootCert.key")));

    String dn = "CN=testIssued, O=testOrg";

    KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize);
    X509Certificate x509Certificate = CertificateUtils.generateIssuedCertificate(dn, keyPair.getPublic(),
            issuer, issuerKeyPair, signingAlgorithm, days);
    assertEquals(dn, x509Certificate.getSubjectX500Principal().toString());
    assertEquals(issuer.getSubjectX500Principal().toString(),
            x509Certificate.getIssuerX500Principal().toString());
    assertEquals(keyPair.getPublic(), x509Certificate.getPublicKey());

    Date notAfter = x509Certificate.getNotAfter();
    assertTrue(notAfter.after(inFuture(days - 1)));
    assertTrue(notAfter.before(inFuture(days + 1)));

    Date notBefore = x509Certificate.getNotBefore();
    assertTrue(notBefore.after(inFuture(-1)));
    assertTrue(notBefore.before(inFuture(1)));

    assertEquals(signingAlgorithm, x509Certificate.getSigAlgName());
    assertEquals(keyPairAlgorithm, x509Certificate.getPublicKey().getAlgorithm());

    x509Certificate.verify(issuerKeyPair.getPublic());
}

From source file:org.gluu.oxtrust.action.ManageCertificateAction.java

private void loadCert(X509Certificate cert) {
    if (cert != null) {
        String issuerDN = cert.getIssuerX500Principal().getName();
        String[] values = issuerDN.split("(?<!\\\\),");
        for (String value : values) {
            String[] keyValue = value.split("=");
            issuer.put(keyValue[0], keyValue[1]);
        }//from   w w w . ja  v a2s.  c  om
        String subjectDN = cert.getSubjectX500Principal().getName();
        values = subjectDN.split("(?<!\\\\),");
        for (String value : values) {
            String[] keyValue = value.split("=");
            subject.put(keyValue[0], keyValue[1]);
        }
        subject.put("validUntil", StringHelper.toString(cert.getNotAfter()));
        subject.put("validAfter", StringHelper.toString(cert.getNotBefore()));
    }
}

From source file:be.fedict.trust.ocsp.OcspTrustLinker.java

public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData) {
    URI ocspUri = getOcspUri(childCertificate);
    if (null == ocspUri) {
        return null;
    }//from w  ww. j  av a  2  s  . c om
    LOG.debug("OCSP URI: " + ocspUri);

    OCSPResp ocspResp = this.ocspRepository.findOcspResponse(ocspUri, childCertificate, certificate);
    if (null == ocspResp) {
        LOG.debug("OCSP response not found");
        return null;
    }

    int ocspRespStatus = ocspResp.getStatus();
    if (OCSPResponseStatus.SUCCESSFUL != ocspRespStatus) {
        LOG.debug("OCSP response status: " + ocspRespStatus);
        return null;
    }

    Object responseObject;
    try {
        responseObject = ocspResp.getResponseObject();
    } catch (OCSPException e) {
        LOG.debug("OCSP exception: " + e.getMessage(), e);
        return null;
    }
    BasicOCSPResp basicOCSPResp = (BasicOCSPResp) responseObject;

    try {
        X509Certificate[] responseCertificates = basicOCSPResp.getCerts(BouncyCastleProvider.PROVIDER_NAME);
        for (X509Certificate responseCertificate : responseCertificates) {
            LOG.debug("OCSP response cert: " + responseCertificate.getSubjectX500Principal());
            LOG.debug("OCSP response cert issuer: " + responseCertificate.getIssuerX500Principal());
        }
        TrustLinkerResult trustResult = TrustValidator
                .checkSignatureAlgorithm(basicOCSPResp.getSignatureAlgName());
        if (!trustResult.isValid())
            return trustResult;

        if (0 == responseCertificates.length) {
            /*
             * This means that the OCSP response has been signed by the
             * issuing CA itself.
             */
            boolean verificationResult = basicOCSPResp.verify(certificate.getPublicKey(),
                    BouncyCastleProvider.PROVIDER_NAME);
            if (false == verificationResult) {
                LOG.debug("OCSP response signature invalid");
                return null;
            }

        } else {
            /*
             * We're dealing with a dedicated authorized OCSP Responder
             * certificate, or of course with a CA that issues the OCSP
             * Responses itself.
             */

            X509Certificate ocspResponderCertificate = responseCertificates[0];
            boolean verificationResult = basicOCSPResp.verify(ocspResponderCertificate.getPublicKey(),
                    BouncyCastleProvider.PROVIDER_NAME);
            if (false == verificationResult) {
                LOG.debug("OCSP Responser response signature invalid");
                return null;
            }
            if (false == Arrays.equals(certificate.getEncoded(), ocspResponderCertificate.getEncoded())) {
                // check certificate signature
                trustResult = TrustValidator.checkSignatureAlgorithm(ocspResponderCertificate.getSigAlgName());
                if (!trustResult.isValid()) {
                    return trustResult;
                }

                X509Certificate issuingCaCertificate;
                if (responseCertificates.length < 2) {
                    LOG.debug("OCSP responder complete certificate chain missing");
                    /*
                     * Here we assume that the OCSP Responder is directly
                     * signed by the CA.
                     */
                    issuingCaCertificate = certificate;
                } else {
                    issuingCaCertificate = responseCertificates[1];
                    /*
                     * Is next check really required?
                     */
                    if (false == certificate.equals(issuingCaCertificate)) {
                        LOG.debug("OCSP responder certificate not issued by CA");
                        return null;
                    }
                }
                // check certificate signature
                trustResult = TrustValidator.checkSignatureAlgorithm(issuingCaCertificate.getSigAlgName());
                if (!trustResult.isValid()) {
                    return trustResult;
                }

                PublicKeyTrustLinker publicKeyTrustLinker = new PublicKeyTrustLinker();
                trustResult = publicKeyTrustLinker.hasTrustLink(ocspResponderCertificate, issuingCaCertificate,
                        validationDate, revocationData);
                if (null != trustResult) {
                    if (!trustResult.isValid()) {
                        LOG.debug("OCSP responder not trusted");
                        return null;
                    }
                }
                if (null == ocspResponderCertificate
                        .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())) {
                    LOG.debug("OCSP Responder certificate should have id-pkix-ocsp-nocheck");
                    /*
                     * TODO: perform CRL validation on the OCSP Responder
                     * certificate. On the other hand, do we really want to
                     * check the checker?
                     */
                    return null;
                }
                List<String> extendedKeyUsage;
                try {
                    extendedKeyUsage = ocspResponderCertificate.getExtendedKeyUsage();
                } catch (CertificateParsingException e) {
                    LOG.debug("OCSP Responder parsing error: " + e.getMessage(), e);
                    return null;
                }
                if (null == extendedKeyUsage) {
                    LOG.debug("OCSP Responder certificate has no extended key usage extension");
                    return null;
                }
                if (false == extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) {
                    LOG.debug("OCSP Responder certificate should have a OCSPSigning extended key usage");
                    return null;
                }
            } else {
                LOG.debug("OCSP Responder certificate equals the CA certificate");
            }
        }
    } catch (NoSuchProviderException e) {
        LOG.debug("JCA provider exception: " + e.getMessage(), e);
        return null;
    } catch (OCSPException e) {
        LOG.debug("OCSP exception: " + e.getMessage(), e);
        return null;
    } catch (CertificateEncodingException e) {
        LOG.debug("certificate encoding error: " + e.getMessage(), e);
        return null;
    }

    CertificateID certificateId;
    try {
        certificateId = new CertificateID(CertificateID.HASH_SHA1, certificate,
                childCertificate.getSerialNumber());
    } catch (OCSPException e) {
        LOG.debug("OCSP exception: " + e.getMessage(), e);
        return null;
    }

    SingleResp[] singleResps = basicOCSPResp.getResponses();
    for (SingleResp singleResp : singleResps) {
        CertificateID responseCertificateId = singleResp.getCertID();
        if (false == certificateId.equals(responseCertificateId)) {
            continue;
        }
        Date thisUpdate = singleResp.getThisUpdate();
        LOG.debug("OCSP thisUpdate: " + thisUpdate);
        LOG.debug("OCSP nextUpdate: " + singleResp.getNextUpdate());
        long dt = Math.abs(thisUpdate.getTime() - validationDate.getTime());
        if (dt > this.freshnessInterval) {
            LOG.warn("freshness interval exceeded: " + dt + " milliseconds");
            continue;
        }
        if (null == singleResp.getCertStatus()) {
            LOG.debug("OCSP OK for: " + childCertificate.getSubjectX500Principal());
            addRevocationData(revocationData, ocspResp);
            return new TrustLinkerResult(true);
        } else {
            LOG.debug("OCSP certificate status: " + singleResp.getCertStatus().getClass().getName());
            if (singleResp.getCertStatus() instanceof RevokedStatus) {
                LOG.debug("OCSP status revoked");
            }
            addRevocationData(revocationData, ocspResp);
            return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
                    "certificate revoked by OCSP");
        }
    }

    LOG.debug("no matching OCSP response entry");
    return null;
}

From source file:org.jscep.client.Client.java

/**
 * Retrieves the certificate corresponding to the provided serial number.
 * <p>/*from  www. j  a v  a 2s.  c o m*/
 * This request relates only to the current CA certificate. If the CA
 * certificate has changed since the requested certificate was issued, this
 * operation will fail.
 * <p>
 * This method provides support for SCEP servers with multiple profiles.
 *
 * @param identity
 *            the identity of the client.
 * @param key
 *            the private key to sign the SCEP request.
 * @param serial
 *            the serial number of the requested certificate.
 * @param profile
 *            the SCEP server profile.
 * @return the certificate store containing the requested certificate.
 * @throws ClientException
 *             if any client error occurs.
 * @throws OperationFailureException
 *             if the SCEP server refuses to service the request.
 */
public CertStore getCertificate(final X509Certificate identity, final PrivateKey key, final BigInteger serial,
        final String profile) throws OperationFailureException, ClientException {
    LOGGER.debug("Retriving certificate from CA");
    // TRANSACTIONAL
    // Certificate query
    final CertStore store = getCaCertificate(profile);
    CertStoreInspector certs = inspectorFactory.getInstance(store);
    final X509Certificate ca = certs.getIssuer();

    X500Name name = new X500Name(ca.getIssuerX500Principal().toString());
    IssuerAndSerialNumber iasn = new IssuerAndSerialNumber(name, serial);
    Transport transport = createTransport(profile);
    final Transaction t = new NonEnrollmentTransaction(transport, getEncoder(identity, key, profile),
            getDecoder(identity, key, profile), iasn, MessageType.GET_CERT);

    State state;
    try {
        state = t.send();
    } catch (TransactionException e) {
        throw new ClientException(e);
    }

    if (state == State.CERT_ISSUED) {
        return t.getCertStore();
    } else if (state == State.CERT_REQ_PENDING) {
        throw new IllegalStateException();
    } else {
        throw new OperationFailureException(t.getFailInfo());
    }
}

From source file:mitm.common.security.certificate.X509CertificateInspector.java

public X509CertificateInspector(X509Certificate certificate) throws CertificateParsingException, IOException {
    super(certificate);

    this.certificate = certificate;

    subjectAltNames = new AltNamesInspector(certificate);
    subjectInspector = new X500PrincipalInspector(certificate.getSubjectX500Principal());
    issuerInspector = new X500PrincipalInspector(certificate.getIssuerX500Principal());
}

From source file:be.fedict.eid.applet.service.signer.facets.KeyInfoSignatureFacet.java

public void postSign(Element signatureElement, List<X509Certificate> signingCertificateChain) {
    LOG.debug("postSign");

    String signatureNamespacePrefix = signatureElement.getPrefix();

    /*/* w  w w .j a  v a 2  s  .  c o  m*/
     * Make sure we insert right after the ds:SignatureValue element, just
     * before the first ds:Object element.
     */
    Node nextSibling;
    NodeList objectNodeList = signatureElement.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
            "Object");
    if (0 == objectNodeList.getLength()) {
        nextSibling = null;
    } else {
        nextSibling = objectNodeList.item(0);
    }

    /*
     * Construct the ds:KeyInfo element using JSR 105.
     */
    KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());
    List<Object> x509DataObjects = new LinkedList<Object>();
    X509Certificate signingCertificate = signingCertificateChain.get(0);

    List<Object> keyInfoContent = new LinkedList<Object>();

    if (this.includeKeyValue) {
        KeyValue keyValue;
        try {
            keyValue = keyInfoFactory.newKeyValue(signingCertificate.getPublicKey());
        } catch (KeyException e) {
            throw new RuntimeException("key exception: " + e.getMessage(), e);
        }
        keyInfoContent.add(keyValue);
    }

    if (this.includeIssuerSerial) {
        x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(
                signingCertificate.getIssuerX500Principal().toString(), signingCertificate.getSerialNumber()));
    }

    if (this.includeEntireCertificateChain) {
        for (X509Certificate certificate : signingCertificateChain) {
            x509DataObjects.add(certificate);
        }
    } else {
        x509DataObjects.add(signingCertificate);
    }

    if (false == x509DataObjects.isEmpty()) {
        X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects);
        keyInfoContent.add(x509Data);
    }
    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent);
    DOMKeyInfo domKeyInfo = (DOMKeyInfo) keyInfo;

    Key key = new Key() {
        private static final long serialVersionUID = 1L;

        public String getAlgorithm() {
            return null;
        }

        public byte[] getEncoded() {
            return null;
        }

        public String getFormat() {
            return null;
        }
    };

    XMLSignContext xmlSignContext = new DOMSignContext(key, signatureElement);
    DOMCryptoContext domCryptoContext = (DOMCryptoContext) xmlSignContext;
    try {
        domKeyInfo.marshal(signatureElement, nextSibling, signatureNamespacePrefix, domCryptoContext);
    } catch (MarshalException e) {
        throw new RuntimeException("marshall error: " + e.getMessage(), e);
    }
}