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:be.fedict.trust.service.bean.TrustDomainServiceBean.java

/**
 * {@inheritDoc}/*from  ww w  .  ja  v a 2s.  c  o m*/
 */
public TrustPointEntity addTrustPoint(String crlRefreshCronSchedule, byte[] certificateBytes)
        throws TrustPointAlreadyExistsException, CertificateException, InvalidCronExpressionException {

    LOG.debug("add trust point");

    X509Certificate certificate = getCertificate(certificateBytes);

    // add CA
    if (null != this.certificateAuthorityDAO.findCertificateAuthority(certificate)) {
        LOG.error("trust point already exist: " + certificate.getSubjectX500Principal().toString());
        throw new TrustPointAlreadyExistsException();
    }
    CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO
            .addCertificateAuthority(certificate, null);

    // add trust point
    TrustPointEntity trustPoint = this.trustDomainDAO.addTrustPoint(crlRefreshCronSchedule,
            certificateAuthority);

    // manage relationship
    certificateAuthority.setTrustPoint(trustPoint);

    // start timer
    this.schedulingService.startTimer(trustPoint);

    return trustPoint;
}

From source file:ee.sk.digidoc.SignedDoc.java

/**
 * Returns certificates DN field in RFC1779 format
 * @param cert certificate/*from   ww  w . ja  v  a  2 s . c o m*/
 * @return DN field
 */
private static String getDN(X509Certificate cert) {
    return cert.getSubjectX500Principal().getName("RFC1779");
}

From source file:be.fedict.eid.dss.model.bean.TrustValidationServiceBean.java

public void validate(TimeStampToken timeStampToken, List<OCSPResp> ocspResponses, List<X509CRL> crls)
        throws CertificateEncodingException, TrustDomainNotFoundException, RevocationDataNotFoundException,
        ValidationFailedException, NoSuchAlgorithmException, NoSuchProviderException, CMSException,
        CertStoreException, IOException {
    LOG.debug("performing historical TSA validation...");
    String tsaTrustDomain = this.configuration.getValue(ConfigProperty.TSA_TRUST_DOMAIN, String.class);
    LOG.debug("TSA trust domain: " + tsaTrustDomain);

    Date validationDate = timeStampToken.getTimeStampInfo().getGenTime();
    LOG.debug("TSA validation date is TST time: " + validationDate);
    LOG.debug("# TSA ocsp responses: " + ocspResponses.size());
    LOG.debug("# TSA CRLs: " + crls.size());

    /*/*from ww  w  .  j a  va  2 s .  co  m*/
     *Building TSA chain. (Code from eID-applet)
     * 
     */

    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    //X500Principal signerCertIssuer = signerId.getIssuer();

    X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded());

    LOG.debug("signer cert serial number: " + signerCertSerialNumber);
    LOG.debug("signer cert issuer: " + signerCertIssuer);

    // TSP signer certificates retrieval
    CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection",
            BouncyCastleProvider.PROVIDER_NAME);
    Collection<? extends Certificate> certificates = certStore.getCertificates(null);
    X509Certificate signerCert = null;
    Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>();
    for (Certificate certificate : certificates) {
        X509Certificate x509Certificate = (X509Certificate) certificate;
        if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal())
                && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
            signerCert = x509Certificate;
        }
        String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate));
        certificateMap.put(ski, x509Certificate);
        LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski);
    }

    // TSP signer cert path building
    if (null == signerCert) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>();

    X509Certificate tsaIssuer = loadCertificate(
            "be/fedict/eid/dss/CA POLITICA SELLADO DE TIEMPO - COSTA RICA.crt");
    X509Certificate rootCA = loadCertificate("be/fedict/eid/dss/CA RAIZ NACIONAL COSTA RICA.cer");
    LOG.debug("adding to certificate chain: " + signerCert.getSubjectX500Principal());
    tspCertificateChain.add(signerCert);
    LOG.debug("adding to certificate chain: " + tsaIssuer.getSubjectX500Principal());
    tspCertificateChain.add(tsaIssuer);
    LOG.debug("adding to certificate chain: " + rootCA.getSubjectX500Principal());
    tspCertificateChain.add(rootCA);

    /*
     * Perform PKI validation via eID Trust Service.
     */
    getXkms2Client().validate(tsaTrustDomain, tspCertificateChain, validationDate, ocspResponses, crls);
}

From source file:be.fedict.eid.tsl.TrustService.java

public void addServiceHistory(String serviceTypeIdentifier, String serviceName, String servicePreviousStatus,
        DateTime statusPreviousStartingDate, X509Certificate... certificates) {

    ServiceHistoryType serviceHistoryType;
    ServiceHistoryInstanceType serviceHistoryInstanceType;

    if (this.tspService.getServiceHistory() == null) {
        serviceHistoryType = this.objectFactory.createServiceHistoryType();
        this.tspService.setServiceHistory(serviceHistoryType);
    } else {/*  w  ww  . j a  va 2s .c  o  m*/
        serviceHistoryType = this.tspService.getServiceHistory();
    }

    serviceHistoryInstanceType = this.objectFactory.createServiceHistoryInstanceType();

    serviceHistoryInstanceType.setServiceTypeIdentifier(serviceTypeIdentifier);

    InternationalNamesType i18nServiceName = this.objectFactory.createInternationalNamesType();
    List<MultiLangNormStringType> serviceNames = i18nServiceName.getName();
    MultiLangNormStringType serviceNameJaxb = this.objectFactory.createMultiLangNormStringType();
    serviceNames.add(serviceNameJaxb);
    serviceNameJaxb.setLang(Locale.ENGLISH.getLanguage());
    X509Certificate certificate = certificates[0];
    if (null == serviceName) {
        serviceNameJaxb.setValue(certificate.getSubjectX500Principal().toString());
    } else {
        serviceNameJaxb.setValue(serviceName);
    }
    serviceHistoryInstanceType.setServiceName(i18nServiceName);

    DigitalIdentityListType digitalIdentityList = createDigitalIdentityList(certificates);
    serviceHistoryInstanceType.setServiceDigitalIdentity(digitalIdentityList);

    serviceHistoryInstanceType.setServiceStatus(servicePreviousStatus);

    GregorianCalendar statusStartingCalendar;
    if (null == this.statusStartingDate) {
        statusStartingCalendar = new DateTime(certificate.getNotBefore()).toGregorianCalendar();
    } else {
        statusStartingCalendar = this.statusStartingDate.toGregorianCalendar();
    }
    statusStartingCalendar.setTimeZone(TimeZone.getTimeZone("Z"));
    XMLGregorianCalendar statusStartingTime = this.datatypeFactory
            .newXMLGregorianCalendar(statusStartingCalendar);
    serviceHistoryInstanceType.setStatusStartingTime(statusStartingTime);

    serviceHistoryType.getServiceHistoryInstance().add(serviceHistoryInstanceType);

}

From source file:org.apache.http.HC4.conn.ssl.AbstractVerifier.java

public final void verify(final String host, final X509Certificate cert) throws SSLException {
    final boolean ipv4 = InetAddressUtils.isIPv4Address(host);
    final boolean ipv6 = InetAddressUtils.isIPv6Address(host);
    final int subjectType = ipv4 || ipv6 ? DefaultHostnameVerifier.IP_ADDRESS_TYPE
            : DefaultHostnameVerifier.DNS_NAME_TYPE;
    final List<String> subjectAlts = DefaultHostnameVerifier.extractSubjectAlts(cert, subjectType);
    final X500Principal subjectPrincipal = cert.getSubjectX500Principal();
    final String[] cns = getCNs(cert);
    verify(host, cns,//from   w w  w  .  j  av  a 2s .c o m
            subjectAlts != null && !subjectAlts.isEmpty() ? subjectAlts.toArray(new String[subjectAlts.size()])
                    : null);
}

From source file:io.fabric8.kubernetes.api.KubernetesFactory.java

private void configureCaCert(WebClient webClient) {
    try (InputStream pemInputStream = getInputStreamFromDataOrFile(caCertData, caCertFile)) {
        CertificateFactory certFactory = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(pemInputStream);

        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(null);//from   ww  w .  j a  v  a2 s  .  c  o m

        String alias = cert.getSubjectX500Principal().getName();
        trustStore.setCertificateEntry(alias, cert);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit();

        TLSClientParameters params = conduit.getTlsClientParameters();

        if (params == null) {
            params = new TLSClientParameters();
            conduit.setTlsClientParameters(params);
        }

        TrustManager[] existingTrustManagers = params.getTrustManagers();
        TrustManager[] trustManagers;

        if (existingTrustManagers == null || ArrayUtils.isEmpty(existingTrustManagers)) {
            trustManagers = trustManagerFactory.getTrustManagers();
        } else {
            trustManagers = (TrustManager[]) ArrayUtils.addAll(existingTrustManagers,
                    trustManagerFactory.getTrustManagers());
        }

        params.setTrustManagers(trustManagers);

    } catch (Exception e) {
        log.error("Could not create trust manager for " + caCertFile, e);
    }
}

From source file:be.fedict.eid.tsl.TrustService.java

public TrustService(String serviceName, String serviceTypeIdentifier, String serviceStatus,
        DateTime statusStartingDate, X509Certificate... certificates) {
    this.serviceName = serviceName;
    this.statusStartingDate = statusStartingDate;
    this.objectFactory = new ObjectFactory();
    try {/* w w  w. j  av  a2 s  . c  o m*/
        this.datatypeFactory = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException("datatype config error: " + e.getMessage(), e);
    }
    this.eccObjectFactory = new be.fedict.eid.tsl.jaxb.ecc.ObjectFactory();
    this.xadesObjectFactory = new be.fedict.eid.tsl.jaxb.xades.ObjectFactory();

    this.tspService = this.objectFactory.createTSPServiceType();
    TSPServiceInformationType tspServiceInformation = this.objectFactory.createTSPServiceInformationType();
    this.tspService.setServiceInformation(tspServiceInformation);
    tspServiceInformation.setServiceTypeIdentifier(serviceTypeIdentifier);
    InternationalNamesType i18nServiceName = this.objectFactory.createInternationalNamesType();
    List<MultiLangNormStringType> serviceNames = i18nServiceName.getName();
    MultiLangNormStringType serviceNameJaxb = this.objectFactory.createMultiLangNormStringType();
    serviceNames.add(serviceNameJaxb);
    serviceNameJaxb.setLang(Locale.ENGLISH.getLanguage());
    X509Certificate certificate = certificates[0];
    if (null == this.serviceName) {
        serviceNameJaxb.setValue(certificate.getSubjectX500Principal().toString());
    } else {
        serviceNameJaxb.setValue(this.serviceName);
    }
    tspServiceInformation.setServiceName(i18nServiceName);

    DigitalIdentityListType digitalIdentityList = createDigitalIdentityList(certificates);
    tspServiceInformation.setServiceDigitalIdentity(digitalIdentityList);

    tspServiceInformation.setServiceStatus(serviceStatus);

    GregorianCalendar statusStartingCalendar;
    if (null == this.statusStartingDate) {
        statusStartingCalendar = new DateTime(certificate.getNotBefore()).toGregorianCalendar();
    } else {
        statusStartingCalendar = this.statusStartingDate.toGregorianCalendar();
    }
    statusStartingCalendar.setTimeZone(TimeZone.getTimeZone("Z"));
    XMLGregorianCalendar statusStartingTime = this.datatypeFactory
            .newXMLGregorianCalendar(statusStartingCalendar);
    tspServiceInformation.setStatusStartingTime(statusStartingTime);
    /*
    if (null != serviceHistoryStatus){
       this.tspService.setServiceHistory(serviceHistoryStatus);
    }
    */
}

From source file:net.solarnetwork.node.setup.impl.DefaultSetupService.java

@Override
public Principal getNodePrincipal() {
    if (pkiService == null) {
        return null;
    }//from w w  w.  j a va2s .c om
    X509Certificate nodeCert = pkiService.getNodeCertificate();
    if (nodeCert == null) {
        log.debug("No node certificate available, cannot get node principal");
        return null;
    }
    return nodeCert.getSubjectX500Principal();
}

From source file:org.apache.directory.studio.connection.ui.widgets.CertificateInfoComposite.java

private void populateCertificateTree() {
    certificateTree.removeAll();//from  ww  w  .java2  s  .  c  o  m
    valueText.setText(StringUtils.EMPTY);

    IStructuredSelection selection = (IStructuredSelection) hierarchyTreeViewer.getSelection();

    if (selection.size() != 1) {
        return;
    }

    CertificateChainItem certificateItem = (CertificateChainItem) selection.getFirstElement();
    X509Certificate certificate = certificateItem.certificate;

    TreeItem rootItem = new TreeItem(certificateTree, SWT.NONE);
    Map<String, String> attributeMap = getAttributeMap(certificate.getSubjectX500Principal());
    rootItem.setText(attributeMap.get("CN")); //$NON-NLS-1$

    TreeItem certItem = createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.Certificate"), //$NON-NLS-1$
            StringUtils.EMPTY);
    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Version"), //$NON-NLS-1$
            String.valueOf(certificate.getVersion()));
    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.SerialNumber"), //$NON-NLS-1$
            certificate.getSerialNumber().toString(16));
    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Signature"), //$NON-NLS-1$
            certificate.getSigAlgName());

    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Issuer"), //$NON-NLS-1$
            certificate.getIssuerX500Principal().getName());

    TreeItem validityItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Validity"), //$NON-NLS-1$
            StringUtils.EMPTY);
    createTreeItem(validityItem, Messages.getString("CertificateInfoComposite.NotBefore"), //$NON-NLS-1$
            certificate.getNotBefore().toString());
    createTreeItem(validityItem, Messages.getString("CertificateInfoComposite.NotAfter"), //$NON-NLS-1$
            certificate.getNotAfter().toString());

    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Subject"), //$NON-NLS-1$
            certificate.getSubjectX500Principal().getName());

    TreeItem pkiItem = createTreeItem(certItem,
            Messages.getString("CertificateInfoComposite.SubjectPublicKeyInfo"), StringUtils.EMPTY); //$NON-NLS-1$
    createTreeItem(pkiItem, Messages.getString("CertificateInfoComposite.SubjectPublicKeyAlgorithm"), //$NON-NLS-1$
            certificate.getPublicKey().getAlgorithm());

    createTreeItem(pkiItem, Messages.getString("CertificateInfoComposite.SubjectPublicKey"), //$NON-NLS-1$
            new String(Hex.encodeHex(certificate.getPublicKey().getEncoded())));

    TreeItem extItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Extensions"), //$NON-NLS-1$
            StringUtils.EMPTY);
    populateExtensions(extItem, certificate, true);
    populateExtensions(extItem, certificate, false);

    createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.SignatureAlgorithm"), //$NON-NLS-1$
            certificate.getSigAlgName());

    createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.Signature"), //$NON-NLS-1$
            new String(Hex.encodeHex(certificate.getSignature())));

    rootItem.setExpanded(true);
    certItem.setExpanded(true);
    validityItem.setExpanded(true);
    pkiItem.setExpanded(true);
    extItem.setExpanded(true);
}

From source file:org.ejbca.core.protocol.cmp.ConfirmationMessageHandler.java

private void signResponse(CmpConfirmResponseMessage cresp, BaseCmpMessage msg) {

    // Get the CA that should sign the response
    CAInfo cainfo;//w w  w.ja v a2s  . com
    try {
        cainfo = getCAInfo(msg.getRecipient().getName().toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug("Using CA '" + cainfo.getName() + "' to sign Certificate Confirm message");
        }
        X509Certificate cacert = (X509Certificate) cainfo.getCertificateChain().iterator().next();
        // We use the actual asn.1 encoding from the cacert subjectDN here. This ensures that the DN is exactly as 
        // encoded in the certificate (which it should be).
        // If we use only the cainfo.getSubjectDN we will get "EJBCA encoding", and this may not be the same if the 
        // CA certificate comes from an external CA that encodes thing differently than EJBCA.
        cresp.setSender(new GeneralName(X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded())));

        try {
            CAToken catoken = cainfo.getCAToken();
            final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(catoken.getCryptoTokenId());
            cresp.setSignKeyInfo(cainfo.getCertificateChain(),
                    cryptoToken
                            .getPrivateKey(catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)),
                    cryptoToken.getSignProviderName());
            if (msg.getHeader().getProtectionAlg() != null) {
                cresp.setPreferredDigestAlg(AlgorithmTools
                        .getDigestFromSigAlg(msg.getHeader().getProtectionAlg().getAlgorithm().getId()));
            }

        } catch (CryptoTokenOfflineException e) {
            LOG.error("Exception during CMP response signing: ", e);
        }

    } catch (CADoesntExistsException e1) {
        LOG.error("Exception during CMP response signing: ", e1);
    }
}