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:test.integ.be.fedict.trust.SSLTrustValidatorTest.java

@Test
public void testValidation() throws Exception {
    Proxy proxy = Proxy.NO_PROXY;
    // Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
    // "proxy.yourict.net", 8080));
    NetworkConfig networkConfig = null; // new
    // NetworkConfig("proxy.yourict.net",
    // 8080);//from   w w w  .  jav a 2  s  .c o  m
    // URL url = new URL("https://eid.belgium.be/"); // OK
    // URL url = new URL("https://www.fortisbanking.be"); // OK
    // URL url = new URL("https://www.e-contract.be/"); // OK
    // URL url = new URL("https://idp.services.belgium.be"); // OK
    // URL url = new URL("https://idp.int.belgium.be"); // OK
    //URL url = new URL("https://test.eid.belgium.be/");
    URL url = new URL("https://www.cloudflare.com/");

    // URL url = new URL("https://www.facebook.com");
    // URL url = new URL("https://www.twitter.com");
    // URL url = new URL("https://www.mozilla.org");
    // URL url = new URL("https://www.verisign.com/");
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(proxy);
    connection.connect();
    Certificate[] serverCertificates = connection.getServerCertificates();
    List<X509Certificate> certificateChain = new LinkedList<>();
    for (Certificate certificate : serverCertificates) {
        X509Certificate x509Cert = (X509Certificate) certificate;
        certificateChain.add(x509Cert);
        LOG.debug("certificate subject: " + x509Cert.getSubjectX500Principal());
        LOG.debug("certificate issuer: " + x509Cert.getIssuerX500Principal());
    }

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate rootCertificate = (X509Certificate) certificateFactory.generateCertificate(
            SSLTrustValidatorTest.class.getResourceAsStream("/ecc/AddTrustExternalCARoot.crt"));
    certificateChain.add(rootCertificate);

    MemoryCertificateRepository certificateRepository = new MemoryCertificateRepository();
    certificateRepository.addTrustPoint(certificateChain.get(certificateChain.size() - 1));

    //certificateRepository.addTrustPoint(rootCertificate);
    TrustValidator trustValidator = new TrustValidator(certificateRepository);
    trustValidator.setAlgorithmPolicy(new AlgorithmPolicy() {

        @Override
        public void checkSignatureAlgorithm(String signatureAlgorithm, Date validationDate)
                throws SignatureException {
            LOG.debug("signature algo: " + signatureAlgorithm);
            // allow all
        }
    });

    // next is kind of a default trust linked pattern.
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator(networkConfig);
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator);

    // operate
    trustValidator.isTrusted(certificateChain);
}

From source file:org.glite.slcs.httpclient.ssl.ExtendedX509TrustManager.java

/**
 * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String
 *      authType)//from   w  w  w .  jav a  2 s  . c  om
 */
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    // use delegate for client certificates
    if (LOG.isDebugEnabled()) {
        LOG.debug("Certificate chain:");
        if (chain != null) {
            for (int i = 0; i < chain.length; i++) {
                X509Certificate certificate = chain[i];
                LOG.debug(i + ": S: " + certificate.getSubjectX500Principal());
                LOG.debug(i + ": I: " + certificate.getIssuerX500Principal());
            }
        }
    }
    defaultTrustManager_.checkClientTrusted(chain, authType);
}

From source file:be.fedict.trust.service.dao.bean.TrustDomainDAOBean.java

/**
 * {@inheritDoc}// w w  w  . ja va 2 s  . co m
 */
public EndEntityConstraintEntity addEndEntityConstraint(TrustDomainEntity trustDomain,
        X509Certificate certificate) {

    String issuerName = certificate.getIssuerX500Principal().getName();
    BigInteger serialNumber = certificate.getSerialNumber();
    EndEntityConstraintEntity endEntityCertificateConstraint = new EndEntityConstraintEntity(trustDomain,
            issuerName, serialNumber);
    this.entityManager.persist(endEntityCertificateConstraint);
    TrustDomainEntity attachedTrustDomain = findTrustDomain(trustDomain.getName());
    attachedTrustDomain.getCertificateConstraints().add(endEntityCertificateConstraint);
    return endEntityCertificateConstraint;
}

From source file:be.fedict.eid.idp.common.saml2.Saml2Util.java

private static boolean isSelfSigned(X509Certificate certificate) {

    return certificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal());
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

private static X509Certificate[] establishTrust(X509Certificate cert, List<X509Certificate> compCerts)
        throws CryptoException {
    /*//ww  w  . j  av a 2s  .  c o m
     * Check whether or not a trust path exists between the supplied X.509
     * certificate and and the supplied comparison certificates , ie that a
     * chain of trust exists between the certificate and a self-signed
     * trusted certificate in the comparison set
     */

    for (int i = 0; i < compCerts.size(); i++) {
        X509Certificate compCert = compCerts.get(i);

        // Verify of certificate issuer is sam as comparison certificate's subject
        if (cert.getIssuerX500Principal().equals(compCert.getSubjectX500Principal())) {
            // Verify if the comparison certificate's private key was used to sign the certificate
            if (X509CertUtil.verifyCertificate(cert, compCert)) {
                // If the comparision certificate is self-signed then a chain of trust exists
                if (compCert.getSubjectX500Principal().equals(compCert.getIssuerX500Principal())) {
                    return new X509Certificate[] { cert, compCert };
                }

                /*
                 * Otherwise try and establish a chain of trust from the
                 * comparison certificate against the other comparison certificates
                 */
                X509Certificate[] tmpChain = establishTrust(compCert, compCerts);
                if (tmpChain != null) {
                    X509Certificate[] trustChain = new X509Certificate[tmpChain.length + 1];

                    trustChain[0] = cert;

                    System.arraycopy(tmpChain, 0, trustChain, 1, tmpChain.length);

                    return trustChain;
                }
            }
        }
    }

    return null; // No chain of trust
}

From source file:org.signserver.admin.cli.defaultimpl.WSAuditorsCommand.java

@Override
public int execute(String... args)
        throws IllegalCommandArgumentsException, CommandFailureException, UnexpectedCommandFailureException {
    try {//from  ww w  .  j  av  a 2 s.co  m
        // Parse the command line
        parseCommandLine(new GnuParser().parse(OPTIONS, args));
    } catch (ParseException ex) {
        throw new IllegalCommandArgumentsException(ex.getMessage());
    }
    validateOptions();

    try {
        final String admins = getGlobalConfigurationSession().getGlobalConfiguration()
                .getProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSAUDITORS");
        final List<Entry> entries = parseAdmins(admins);

        if (LIST.equals(operation)) {
            final StringBuilder buff = new StringBuilder();
            buff.append("Authorized auditors:");
            buff.append("\n");
            for (Entry entry : entries) {
                buff.append(String.format("%-20s %s", entry.getCertSerialNo(), entry.getIssuerDN()));
                buff.append("\n");
            }
            getOutputStream().println(buff.toString());
        } else if (ADD.equals(operation)) {
            if (cert == null) {
                // serial number and issuer DN was entered manually
                entries.add(new Entry(certSerialNo, issuerDN));
            } else {
                // read serial number and issuer DN from cert file
                X509Certificate certificate = SignServerUtil.getCertFromFile(cert);
                String sn = certificate.getSerialNumber().toString(16);
                String dn = certificate.getIssuerX500Principal().getName();

                CertTools.BasicX509NameTokenizer tok = new CertTools.BasicX509NameTokenizer(dn);
                StringBuilder buf = new StringBuilder();

                while (tok.hasMoreTokens()) {
                    final String token = tok.nextToken();
                    buf.append(token);
                    if (tok.hasMoreTokens()) {
                        buf.append(", ");
                    }
                }

                entries.add(new Entry(sn, buf.toString()));
            }
            getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSAUDITORS",
                    serializeAdmins(entries));
            getOutputStream().println("Auditor added");
        } else if (REMOVE.equals(operation)) {
            if (entries.remove(new Entry(certSerialNo, issuerDN))) {
                getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSAUDITORS",
                        serializeAdmins(entries));
                getOutputStream().println("Auditor removed");
            } else {
                getErrorStream().println("No such auditor");
            }
        }
        return 0;
    } catch (EJBException eJBException) {
        if (eJBException.getCausedByException() instanceof IllegalArgumentException) {
            getErrorStream().println(eJBException.getMessage());
            return -2;
        } else {
            throw new UnexpectedCommandFailureException(eJBException);
        }
    } catch (Exception e) {
        throw new UnexpectedCommandFailureException(e);
    }
}

From source file:org.viafirma.nucleo.X509.X509Handler.java

/**
 * Retorna el certificado emisor del certificado actual
 * /*from   w  w  w  .j  av a 2  s .c  o  m*/
 * @param certificado
 * @param certificadosConfianza
 * @return
 * @throws ExcepcionErrorInterno  No se ha encontrado un certificado asociado vlido.
 */
public X509Certificate getEmisor(X509Certificate certificado, Set<TrustAnchor> certificadosConfianza)
        throws ExcepcionErrorInterno {
    // Si no es un certificado autoemitido
    if (certificado.getIssuerX500Principal().getName()
            .equals(certificado.getSubjectX500Principal().getName())) {
        // El certificado esta autofirmado, no hay emisor.
        return null;
    } else {
        // Busco el emisor indicado.
        for (TrustAnchor trustAnchor : certificadosConfianza) {
            if (trustAnchor.getTrustedCert().getSubjectX500Principal().getName()
                    .equals(certificado.getIssuerX500Principal().getName())) {
                // Encontrado el certificado de confianza.
                return trustAnchor.getTrustedCert();
            }
        }
    }
    log.error("No hay ningun certificado asociado a :" + certificado.getIssuerX500Principal().getName()
            + " es necesaria su instalacin para poder gestionar este tpo de certificados.");
    throw new ExcepcionErrorInterno(CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA);
}

From source file:be.fedict.trust.linker.PublicKeyTrustLinker.java

@Override
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy)
        throws TrustLinkerResultException, Exception {
    if (false == childCertificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) {
        LOG.debug("child certificate issuer not the same as the issuer certificate subject");
        LOG.debug("child certificate: " + childCertificate.getSubjectX500Principal());
        LOG.debug("certificate: " + certificate.getSubjectX500Principal());
        LOG.debug("child certificate issuer: " + childCertificate.getIssuerX500Principal());
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                "child certificate issuer not the same as the issuer certificate subject");
    }/*from ww w.  j ava  2 s  .c  o m*/
    try {
        childCertificate.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.debug("verification error: " + e.getMessage(), e);
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_SIGNATURE,
                "verification error: " + e.getMessage());
    }

    algorithmPolicy.checkSignatureAlgorithm(childCertificate.getSigAlgOID(), validationDate);

    if (true == childCertificate.getNotAfter().after(certificate.getNotAfter())) {
        LOG.warn("child certificate validity end is after certificate validity end");
        LOG.warn("child certificate validity end: " + childCertificate.getNotAfter());
        LOG.warn("certificate validity end: " + certificate.getNotAfter());
    }
    if (true == childCertificate.getNotBefore().before(certificate.getNotBefore())) {
        LOG.warn("child certificate validity begin before certificate validity begin");
        LOG.warn("child certificate validity begin: " + childCertificate.getNotBefore());
        LOG.warn("certificate validity begin: " + certificate.getNotBefore());
    }
    if (true == validationDate.before(childCertificate.getNotBefore())) {
        LOG.debug("certificate is not yet valid");
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate is not yet valid");
    }
    if (true == validationDate.after(childCertificate.getNotAfter())) {
        LOG.debug("certificate already expired");
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate already expired");
    }
    if (-1 == certificate.getBasicConstraints()) {
        LOG.debug("certificate not a CA: " + certificate.getSubjectX500Principal());
        /*
         * http://www.valicert.com/ Root CA has no CA flag set. Actually
         * this is in violation with 4.2.1.10 Basic Constraints of RFC2459.
         */
        try {
            certificate.verify(certificate.getPublicKey());
            LOG.warn("allowing self-signed Root CA without CA flag set");
        } catch (Exception e) {
            throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST, "certificate not a CA");
        }
    }
    if (0 == certificate.getBasicConstraints() && -1 != childCertificate.getBasicConstraints()) {
        LOG.debug("child should not be a CA");
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST, "child should not be a CA");
    }

    /*
     * SKID/AKID sanity check
     */
    boolean isCa = isCa(certificate);
    boolean isChildCa = isCa(childCertificate);

    byte[] subjectKeyIdentifierData = certificate.getExtensionValue(Extension.subjectKeyIdentifier.getId());
    byte[] authorityKeyIdentifierData = childCertificate
            .getExtensionValue(Extension.authorityKeyIdentifier.getId());

    if (isCa && null == subjectKeyIdentifierData) {
        LOG.debug("certificate is CA and MUST contain a Subject Key Identifier");
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                "certificate is CA and  MUST contain a Subject Key Identifier");
    }

    if (isChildCa && null == authorityKeyIdentifierData && null != subjectKeyIdentifierData) {
        LOG.error("child certificate is CA and MUST contain an Authority Key Identifier");
        // return new TrustLinkerResult(false,
        // TrustLinkerResultReason.INVALID_TRUST,
        // "child certificate is CA and MUST contain an Authority Key Identifier");
    }

    if (null != subjectKeyIdentifierData && null != authorityKeyIdentifierData) {
        AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier
                .getInstance(JcaX509ExtensionUtils.parseExtensionValue(authorityKeyIdentifierData));
        SubjectKeyIdentifier subjectKeyIdentifier = SubjectKeyIdentifier
                .getInstance(JcaX509ExtensionUtils.parseExtensionValue(subjectKeyIdentifierData));
        if (!Arrays.equals(authorityKeyIdentifier.getKeyIdentifier(),
                subjectKeyIdentifier.getKeyIdentifier())) {
            LOG.debug(
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
            throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
        }
    }

    /*
     * We don't check pathLenConstraint since this one is only there to
     * protect the PKI business.
     */
    /*
     * Keep in mind that this trust linker can never return TRUSTED.
     */
    return TrustLinkerResult.UNDECIDED;
}

From source file:net.solarnetwork.node.setup.test.DefaultKeystoreServiceTest.java

@Test
public void generatePKCS12Keystore() throws Exception {
    saveCASignedCert();/* w  ww .j  av  a2 s.  c om*/
    reset(setupIdentityDao);

    SetupIdentityInfo info = new SetupIdentityInfo(1L, TEST_CONF_VALUE, "localhost", 80, false, TEST_PW_VALUE);
    expect(setupIdentityDao.getSetupIdentityInfo()).andReturn(info).atLeastOnce();

    replay(setupIdentityDao);

    String keystoreData = service.generatePKCS12KeystoreString("foobar");

    assertNotNull(keystoreData);

    byte[] data = Base64.decodeBase64(keystoreData);

    KeyStore keyStore = KeyStore.getInstance("pkcs12");
    keyStore.load(new ByteArrayInputStream(data), "foobar".toCharArray());
    Certificate cert = keyStore.getCertificate("node");
    assertNotNull(cert);
    assertTrue(cert instanceof X509Certificate);
    X509Certificate nodeCert = (X509Certificate) cert;
    assertEquals(new X500Principal(TEST_DN), nodeCert.getSubjectX500Principal());
    assertEquals(CA_CERT.getSubjectX500Principal(), nodeCert.getIssuerX500Principal());
}

From source file:com.google.u2f.gaedemo.storage.TokenStorageData.java

public JsonObject toJson() {
    X509Certificate x509cert = getSecurityKeyData().getAttestationCertificate();
    JsonObject json = new JsonObject();
    json.addProperty("enrollment_time", enrollmentTime);
    json.add("transports", getJsonTransports());
    json.addProperty("key_handle", Hex.encodeHexString(keyHandle));
    json.addProperty("public_key", Hex.encodeHexString(publicKey));
    json.addProperty("issuer", x509cert.getIssuerX500Principal().getName());

    try {/*from  w w  w.j  av a2 s.c om*/
        AndroidKeyStoreAttestation androidKeyStoreAttestation = AndroidKeyStoreAttestation.Parse(x509cert);
        if (androidKeyStoreAttestation != null) {
            json.add("android_attestation", androidKeyStoreAttestation.toJson());
        }
    } catch (CertificateParsingException e) {
        throw new RuntimeException(e);
    }

    return json;
}