Example usage for javax.security.auth.x500 X500Principal equals

List of usage examples for javax.security.auth.x500 X500Principal equals

Introduction

In this page you can find the example usage for javax.security.auth.x500 X500Principal equals.

Prototype

public boolean equals(Object o) 

Source Link

Document

Compares the specified Object with this X500Principal for equality.

Usage

From source file:Main.java

public static X509Certificate[] getSortedPath(X509Certificate[] inpath) throws IOException {
    try {// w  w  w . j  av a  2 s  . co  m
        // Build/check path
        int n = 0;
        int[] idx = new int[inpath.length];
        int[] jidx = new int[inpath.length];
        boolean[] done = new boolean[inpath.length];
        for (int i = 0; i < inpath.length; i++) {
            X500Principal p = inpath[i].getIssuerX500Principal();
            idx[i] = -1;
            for (int j = 0; j < inpath.length; j++) {
                if (j == i || done[j])
                    continue;
                if (p.equals(inpath[j].getSubjectX500Principal())) // J is certifying I
                {
                    n++;
                    idx[i] = j;
                    jidx[j] = i;
                    done[j] = true;
                    inpath[i].verify(inpath[j].getPublicKey());
                    break;
                }
            }
        }
        if (n != (inpath.length - 1)) {
            throw new IOException("X509Certificate elements contain multiple or broken cert paths");
        }

        // Path OK, now sort it
        X509Certificate[] certpath = new X509Certificate[inpath.length];
        for (int i = 0; i < inpath.length; i++) {
            if (idx[i] < 0) // Must be the highest
            {
                certpath[n] = inpath[i];
                while (--n >= 0) {
                    certpath[n] = inpath[i = jidx[i]];
                }
                break;
            }
        }
        return certpath;
    } catch (GeneralSecurityException gse) {
        throw new IOException(gse);
    }
}

From source file:org.sandrob.android.net.http.HttpsConnection.java

private static String getCertificateAlias(X509Certificate cert) {
    X500Principal subject = cert.getSubjectX500Principal();
    X500Principal issuer = cert.getIssuerX500Principal();

    String sSubjectCN = getCommonName(subject);

    // Could not get a subject CN - return blank
    if (sSubjectCN == null) {
        return "";
    }//from  w  w  w .  ja  v a 2  s .c o  m

    String sIssuerCN = getCommonName(issuer);

    // Self-signed certificate or could not get an issuer CN
    if (subject.equals(issuer) || sIssuerCN == null) {
        // Alias is the subject CN
        return sSubjectCN;
    }
    // else non-self-signed certificate
    // Alias is the subject CN followed by the issuer CN in parenthesis
    return MessageFormat.format("{0} ({1})", sSubjectCN, sIssuerCN);
}

From source file:be.fedict.eid.dss.spi.utils.XAdESUtils.java

public static void verifyTimeStampTokenSignature(TimeStampToken timeStampToken)
        throws XAdESValidationException {

    try {//from   w  w w  . j a  v a2  s  .c om
        SignerId signerId = timeStampToken.getSID();
        BigInteger signerCertSerialNumber = signerId.getSerialNumber();
        //X500Principal signerCertIssuer = signerId.getIssuer();
        X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded());

        CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection",
                BouncyCastleProvider.PROVIDER_NAME);
        Collection<? extends Certificate> certificates = certStore.getCertificates(null);
        X509Certificate tsaCertificate = null;
        for (Certificate certificate : certificates) {
            X509Certificate x509Certificate = (X509Certificate) certificate;
            if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal())
                    && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
                tsaCertificate = x509Certificate;
                break;
            }
        }

        if (null == tsaCertificate) {
            throw new XAdESValidationException("TSA certificate not present in TST");
        }

        timeStampToken.validate(tsaCertificate, BouncyCastleProvider.PROVIDER_NAME);
    } catch (Exception e) {
        throw new XAdESValidationException(e);
    }
}

From source file:org.apache.directory.studio.connection.core.io.StudioTrustManager.java

/**
 * {@inheritDoc}//from ww  w  .j av  a  2 s. c om
 */
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    // check permanent trusted certificates, return on success
    try {
        X509TrustManager permanentTrustManager = getPermanentTrustManager();
        if (permanentTrustManager != null) {
            permanentTrustManager.checkServerTrusted(chain, authType);
            return;
        }
    } catch (CertificateException ce) {
    }

    // check temporary trusted certificates, return on success
    try {
        X509TrustManager sessionTrustManager = getSessionTrustManager();
        if (sessionTrustManager != null) {
            sessionTrustManager.checkServerTrusted(chain, authType);
            return;
        }
    } catch (CertificateException ce) {
    }

    // below here no manually trusted certificate (either permanent or temporary) matched
    List<ICertificateHandler.FailCause> failCauses = new ArrayList<ICertificateHandler.FailCause>();

    // perform trust check of JVM trust manager
    try {
        jvmTrustManager.checkServerTrusted(chain, authType);
    } catch (CertificateException ce) {
        if (ce instanceof CertificateExpiredException) {
            failCauses.add(FailCause.CertificateExpired);
        } else if (ce instanceof CertificateNotYetValidException) {
            failCauses.add(FailCause.CertificateNotYetValid);
        } else {
            X500Principal issuerX500Principal = chain[0].getIssuerX500Principal();
            X500Principal subjectX500Principal = chain[0].getSubjectX500Principal();
            if (issuerX500Principal.equals(subjectX500Principal)) {
                failCauses.add(FailCause.SelfSignedCertificate);
            } else {
                failCauses.add(FailCause.NoValidCertificationPath);
            }

            try {
                chain[0].checkValidity();
            } catch (CertificateException ve) {
                if (ve instanceof CertificateExpiredException) {
                    failCauses.add(FailCause.CertificateExpired);
                } else if (ve instanceof CertificateNotYetValidException) {
                    failCauses.add(FailCause.CertificateNotYetValid);
                }
            }
        }
    }

    // perform host name verification
    try {
        BrowserCompatHostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();
        hostnameVerifier.verify(host, chain[0]);
    } catch (SSLException ce) {
        failCauses.add(FailCause.HostnameVerificationFailed);
    }

    if (!failCauses.isEmpty()) {
        // either trust check or host name verification
        // ask for confirmation
        ICertificateHandler ch = ConnectionCorePlugin.getDefault().getCertificateHandler();
        ICertificateHandler.TrustLevel trustLevel = ch.verifyTrustLevel(host, chain, failCauses);
        switch (trustLevel) {
        case Permanent:
            ConnectionCorePlugin.getDefault().getPermanentTrustStoreManager().addCertificate(chain[0]);
            break;
        case Session:
            ConnectionCorePlugin.getDefault().getSessionTrustStoreManager().addCertificate(chain[0]);
            break;
        case Not:
            throw new CertificateException(Messages.error__untrusted_certificate);
        }
    }
}

From source file:com.alfaariss.oa.engine.crypto.keystore.KeystoreSigningFactory.java

/**
 * Retrieve alias from the certificate store.
 * @see AbstractSigningFactory#getAliasForX509Cert(
 *  java.lang.String, java.math.BigInteger)
 *///  w w w .  j a  va 2  s.c o  m
@Override
public String getAliasForX509Cert(String issuer, BigInteger serialNumber) throws CryptoException {
    X500Principal issuerRDN = new X500Principal(issuer);
    Certificate cert = null;

    try {
        Enumeration<String> aliases = _certificatestore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            Certificate[] certs = _certificatestore.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain
                cert = _certificatestore.getCertificate(alias);
                if (cert == null) {
                    return null;
                }
            } else {
                cert = certs[0];
            }

            if (cert instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) cert;
                if (serialNumber == null || x509cert.getSerialNumber().compareTo(serialNumber) == 0) {
                    X500Principal certRDN = new X500Principal(x509cert.getIssuerDN().getName());
                    if (certRDN.equals(issuerRDN)) {
                        return alias;
                    }
                }
            }
        }
    } catch (KeyStoreException e) {
        _logger.error("Could not read alias from trust store", e);
        throw new CryptoException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
    }
    return null;
}

From source file:cz.hobrasoft.pdfmu.operation.OperationInspect.java

private CertificateResult showCertInfo(X509Certificate cert) {
    CertificateResult certRes = new CertificateResult();

    { // Self-signed?
        X500Principal principalSubject = cert.getSubjectX500Principal();
        X500Principal principalIssuer = cert.getIssuerX500Principal();
        boolean selfSigned = principalSubject.equals(principalIssuer);
        to.println(String.format("Self-signed: %s", (selfSigned ? "Yes" : "No")));
        certRes.selfSigned = selfSigned;
    }/* ww w  .jav  a2  s .co  m*/

    // Note: More attributes may be available by more direct processing of `cert`
    // than by using `CertificateInfo.get*Fields`.
    { // Subject
        to.indentMore("Subject:");
        certRes.subject = showX500Name(CertificateInfo.getSubjectFields(cert));
        to.indentLess();
    }
    { // Issuer
        to.indentMore("Issuer:");
        certRes.issuer = showX500Name(CertificateInfo.getIssuerFields(cert));
        to.indentLess();
    }

    return certRes;
}

From source file:it.cnr.icar.eric.server.security.authentication.CertificateAuthority.java

private boolean validateChain(Certificate[] certChain) {
    for (int i = 0; i < certChain.length - 1; i++) {
        X500Principal issuerDN = ((X509Certificate) certChain[i]).getIssuerX500Principal();
        X500Principal subjectDN = ((X509Certificate) certChain[i + 1]).getSubjectX500Principal();
        if (!(issuerDN.equals(subjectDN)))
            return false;
    }/*from w  w w  .  j  av a2  s  .  com*/
    return true;
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

private TenantObject getByCa(final X500Principal subjectDn) {

    if (subjectDn == null) {
        return null;
    } else {/* w  w  w .j ava 2 s .c o  m*/
        return tenants.values().stream().filter(t -> subjectDn.equals(t.getTrustedCaSubjectDn())).findFirst()
                .orElse(null);
    }
}

From source file:eu.europa.esig.dss.DSSUtils.java

/**
 * This method compares two {@code X500Principal}s. {@code X500Principal.CANONICAL} and {@code X500Principal.RFC2253} forms are compared.
 * TODO: (Bob: 2014 Feb 20) To be investigated why the standard equals does not work!?
 *
 * @param firstX500Principal//from w w w  .j  a  v  a 2 s.com
 * @param secondX500Principal
 * @return
 */
public static boolean x500PrincipalAreEquals(final X500Principal firstX500Principal,
        final X500Principal secondX500Principal) {
    if ((firstX500Principal == null) || (secondX500Principal == null)) {
        return false;
    }
    if (firstX500Principal.equals(secondX500Principal)) {
        return true;
    }
    final Map<String, String> firstStringStringHashMap = DSSASN1Utils.get(firstX500Principal);
    final Map<String, String> secondStringStringHashMap = DSSASN1Utils.get(secondX500Principal);
    final boolean containsAll = firstStringStringHashMap.entrySet()
            .containsAll(secondStringStringHashMap.entrySet());

    return containsAll;
}

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 av a2s. c  o 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);
}