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.ejbca.core.ejb.ocsp.OcspKeyRenewalSessionBean.java

/**
 * /*from w  ww.  j  a v  a  2  s  . c om*/
 * 
 * @param signerSubjectDN signerSubjectDN subject DN of the signing key to be renewed. The string "all" will result in all keys being renewed
 * @param safetyMargin the number of seconds before actual expiration that a keystore should be renewed
 * @throws CryptoTokenOfflineException if Crypto Token is not available or connected, or key with alias does not exist.
 * @throws InvalidKeyException if the public key in the tokenAndChain can not be used to verify a string signed by the private key, because the key 
 * is wrong or the signature operation fails for other reasons such as a NoSuchAlgorithmException or SignatureException.
 */
private synchronized void renewKeyStores(String signerSubjectDN, long safetyMargin)
        throws InvalidKeyException, CryptoTokenOfflineException {
    //Cancel all running timers
    cancelTimers();
    try {
        final EjbcaWS ejbcaWS = getEjbcaWS();
        if (ejbcaWS == null) {
            if (log.isDebugEnabled()) {
                log.debug(
                        "Could not locate a suitable web service for automatic OCSP key/certificate renewal.");
            }
            return;
        }
        final X500Principal target;
        try {
            target = signerSubjectDN.trim().equalsIgnoreCase(RENEW_ALL_KEYS) ? null
                    : new X500Principal(signerSubjectDN);
        } catch (IllegalArgumentException e) {
            log.error(intres.getLocalizedMessage("ocsp.rekey.triggered.dn.not.valid", signerSubjectDN));
            return;
        }
        final StringBuffer matched = new StringBuffer();
        final StringBuffer unMatched = new StringBuffer();
        for (final OcspSigningCacheEntry ocspSigningCacheEntry : OcspSigningCache.INSTANCE.getEntries()) {
            // Only perform renewal for non CA signing key OCSP signers
            if (!ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) {
                continue;
            }
            final X509Certificate ocspSigningCertificate = ocspSigningCacheEntry.getOcspSigningCertificate();
            final long timeLeftBeforeRenewal = ocspSigningCertificate.getNotAfter().getTime()
                    - new Date().getTime();
            if (timeLeftBeforeRenewal < (1000 * safetyMargin)) {
                final X500Principal src = ocspSigningCertificate.getSubjectX500Principal();
                if (target != null && !src.equals(target)) {
                    unMatched.append(" '" + src.getName() + '\'');
                    continue;
                }
                matched.append(" '" + ocspSigningCertificate.getIssuerX500Principal().getName() + '\'');
                try {
                    renewKeyStore(ejbcaWS, ocspSigningCacheEntry);
                } catch (KeyRenewalFailedException e) {
                    String msg = intres.getLocalizedMessage("ocsp.rekey.failed.unknown.reason", target,
                            e.getLocalizedMessage());
                    log.error(msg, e);
                    continue;
                }
            }
        }
        if (matched.length() < 1 && target != null) {
            log.error(intres.getLocalizedMessage("ocsp.rekey.triggered.dn.not.existing", target.getName(),
                    unMatched));
            return;
        }
        log.info(intres.getLocalizedMessage("ocsp.rekey.triggered", matched));
    } finally {
        //Set new timer to run, even if something breaks.
        addTimer(OcspConfiguration.getRekeyingUpdateTimeInSeconds());
    }
}

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

private void setupOCSPResonderConfig(URL ocspURL, X509Certificate signingCert) {

    if (ocspURL != null) {
        Security.setProperty("ocsp.responderURL", ocspURL.toString());
    }/* w w w .ja va  2s.c o  m*/

    if (signingCert != null) {
        //Setup ocsp.responderCertSubjectName

        if (null != signingCert) {
            String subjectDN = signingCert.getSubjectX500Principal().getName();
            Validate.notEmpty(subjectDN,
                    "Null or empty SubjectX500Principal name extracted from alternative OCSP responder signing cert.");
            Security.setProperty("ocsp.responderCertSubjectName", subjectDN);
        }
    }
}

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

protected String resolveUID(X509Certificate cert) throws SSOAuthenticationException {
    try {/*from w w w .ja  va 2  s. com*/

        // If CN is used, UID is CN

        // If DN is used, we need to resolve it using the credentials store

        // If Certificate is used, we need to resolve it using the credential store

        // If Email is used, we need to resolve it using the credential store

        Principal dn = cert.getSubjectDN();

        java.util.Collection an = (java.util.Collection) cert.getSubjectAlternativeNames();

        X500Principal x500 = cert.getSubjectX500Principal();

        return null;
    } catch (Exception e) {
        throw new SSOAuthenticationException(e);
    }

}

From source file:controller.CCInstance.java

public Certificate hasTrustedIssuerCertificate(final X509Certificate x509c) {
    ArrayList<Certificate> alTrustedCertificates;
    try {//  w  ww . jav a 2 s  .co  m
        alTrustedCertificates = getTrustedCertificatesFromKeystore(getKeystore());
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
            | InvalidAlgorithmParameterException ex) {
        return null;
    }

    if (alTrustedCertificates.isEmpty()) {
        return null;
    }

    for (final Certificate c : alTrustedCertificates) {
        try {
            final X509Certificate x509cc = (X509Certificate) c;
            if (x509c.getIssuerX500Principal().equals(x509cc.getSubjectX500Principal())) {
                return c;
            }
        } catch (Exception e) {
            return null;
        }
    }
    return null;
}

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

private X509Certificate FindCertByDN(X500Principal name) throws Exception {
    KeyStore ks = GetTrustStore();
    if (ks == null) {
        return null;
    }/*from w  w  w .ja v  a2 s . c  om*/
    Enumeration<String> aliases = ks.aliases();
    while (aliases.hasMoreElements()) {
        String nextElement = aliases.nextElement();
        Certificate certificate = ks.getCertificate(nextElement);
        X509Certificate x = (X509Certificate) certificate;
        if (x.getSubjectX500Principal().equals(name)) {
            return x;
        }
    }
    return null;
}

From source file:ee.ria.xroad.common.conf.globalconf.GlobalConfImpl.java

private CertificateProfileInfoProvider getCertProfile(String instanceIdentifier, X509Certificate cert)
        throws Exception {
    X509Certificate caCert = getCaCert(instanceIdentifier, cert);
    SharedParametersV2 p = getSharedParameters(instanceIdentifier);

    String certProfileProviderClass = p.getCaCertsAndCertProfiles().get(caCert);
    if (StringUtils.isBlank(certProfileProviderClass)) {
        throw new CodedException(X_INTERNAL_ERROR, "Could not find certificate profile info for certificate "
                + cert.getSubjectX500Principal().getName());
    }/*  w ww. j  a  v  a 2 s.  c  o  m*/

    return new GetCertificateProfile(certProfileProviderClass).instance();
}

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

private DOMXMLSignature createDetached(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId, final Document inside)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JAXBException, MarshalException,
        XMLSignatureException, ParserConfigurationException, IOException {

    final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);

    // Create references
    List<Reference> references = new ArrayList<Reference>();
    addReferences(documentIterator(inside), references, digestMethod, fac);
    // Create repository
    signContext.setURIDereferencer(new NameBasedDocumentRepository(inside, fac));

    List<XMLObject> objects = new ArrayList<XMLObject>();

    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#");

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, references, inside);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);
    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);/*from w  w  w . jav  a 2 s  . c  om*/

    List<Transform> xadesTranforms = new ArrayList<Transform>();
    Transform exclusiveTransform2 = fac.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    xadesTranforms.add(exclusiveTransform2);
    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod, xadesTranforms,
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    doc.removeChild(doc.getDocumentElement());
    signature.marshal(doc, "ds", signContext);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");

    digestReferences(signContext, references);

    return signature;

}

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

private DOMXMLSignature createEnveloping(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId, Document inside)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JAXBException, MarshalException,
        XMLSignatureException, ParserConfigurationException, IOException {

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);

    List<XMLObject> objects = new ArrayList<XMLObject>();
    List<Reference> references = new ArrayList<Reference>();

    byte[] b64data = Base64.encode(IOUtils.toByteArray(inside.openStream()));

    List<Transform> transforms = new ArrayList<Transform>();
    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#");
    Transform exclusiveTransform = fac.newTransform(CanonicalizationMethod.BASE64,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);//from  w  w w  .j av  a 2  s . c o m

    /* The first reference concern the whole document */
    Reference reference = fac.newReference("#signed-data-" + computeDeterministicId(params), digestMethod,
            transforms, null, "signed-data-ref");
    references.add(reference);

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, reference, MimeType.PLAIN);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");

    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);

    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);

    List<Transform> xadesTranforms = new ArrayList<Transform>();
    Transform exclusiveTransform2 = fac.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    xadesTranforms.add(exclusiveTransform2);
    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod, xadesTranforms,
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    doc.removeChild(doc.getDocumentElement());
    signature.marshal(doc, "ds", signContext);

    Element dsObject = doc.createElementNS(XMLSignature.XMLNS, "Object");
    dsObject.setAttribute("Id", "signed-data-" + computeDeterministicId(params));
    dsObject.setTextContent(new String(b64data));
    doc.getDocumentElement().appendChild(dsObject);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");
    signContext.setIdAttributeNS(dsObject, null, "Id");

    digestReferences(signContext, references);

    return signature;

}

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

private DOMXMLSignature createEnveloped(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, JAXBException, MarshalException, XMLSignatureException {

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    signContext.setURIDereferencer(new URIDereferencer() {

        @Override//  ww w  .j a  v a2 s  . c om
        public Data dereference(URIReference uriReference, XMLCryptoContext context)
                throws URIReferenceException {
            final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
            Data data = fac.getURIDereferencer().dereference(uriReference, context);
            return data;
        }
    });

    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", XMLSignature.XMLNS);

    List<Reference> references = new ArrayList<Reference>();

    /* The first reference concern the whole document */
    List<Transform> transforms = new ArrayList<Transform>();
    transforms.add(fac.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    org.w3c.dom.Document empty;
    try {
        empty = dbf.newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e1) {
        throw new RuntimeException(e1);
    }
    Element xpathEl = empty.createElementNS(XMLSignature.XMLNS, "XPath");
    xpathEl.setTextContent("");
    empty.adoptNode(xpathEl);
    XPathFilterParameterSpec specs = new XPathFilterParameterSpec("not(ancestor-or-self::ds:Signature)");
    DOMTransform t = (DOMTransform) fac.newTransform("http://www.w3.org/TR/1999/REC-xpath-19991116", specs);

    transforms.add(t);
    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);
    Reference reference = fac.newReference("", digestMethod, transforms, null, "xml_ref_id");
    references.add(reference);

    List<XMLObject> objects = new ArrayList<XMLObject>();

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, reference, MimeType.XML);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);
    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);

    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod,
            Collections.singletonList(
                    fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null)),
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    signature.marshal(doc.getDocumentElement(), "ds", signContext);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");

    digestReferences(signContext, references);

    return signature;

}

From source file:be.fedict.trust.TrustValidator.java

private void checkSelfSignedTrust(X509Certificate certificate, Date validationDate)
        throws CertPathValidatorException {
    try {// w w  w . ja v a2 s.co m
        certificate.checkValidity(validationDate);
    } catch (Exception e) {
        this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate validity error: " + e.getMessage());
        throw new CertPathValidatorException(this.result.getMessage());
    }
    if (this.certificateRepository.isTrustPoint(certificate)) {
        return;
    }

    this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
            "self-signed certificate not in repository: " + certificate.getSubjectX500Principal());
    throw new CertPathValidatorException(this.result.getMessage());
}