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:net.solarnetwork.pki.bc.test.BCCertificateServiceTest.java

@Test
public void signCertificate() throws Exception {
    X509Certificate cert = service.generateCertificate(TEST_DN, publicKey, privateKey);
    String csr = service.generatePKCS10CertificateRequestString(cert, privateKey);

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048, new SecureRandom());
    KeyPair caKeypair = keyGen.generateKeyPair();
    X509Certificate caCert = service.generateCertificationAuthorityCertificate(TEST_CA_DN,
            caKeypair.getPublic(), caKeypair.getPrivate());

    X509Certificate signed = service.signCertificate(csr, caCert, caKeypair.getPrivate());
    assertEquals("Issuer", caCert.getSubjectX500Principal(), signed.getIssuerX500Principal());
    assertEquals("Subject", cert.getSubjectX500Principal(), signed.getSubjectX500Principal());
}

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @param cert/*from ww  w. j a v  a 2 s.c om*/
 * @return
 */
public static Tuple getCertDesc(Certificate cert) {

    tstArgIsType("cert", cert, X509Certificate.class);

    X509Certificate x509 = (X509Certificate) cert;
    X500Principal issuer = x509.getIssuerX500Principal();
    X500Principal subj = x509.getSubjectX500Principal();
    Date vs = x509.getNotBefore();
    Date ve = x509.getNotAfter();

    return new Tuple(subj, issuer, vs, ve);
}

From source file:org.casbah.provider.openssl.OpenSslCAProviderTest.java

@Test
public void testGetCACertificate() throws CAProviderException {
    OpenSslCAProvider provider = new OpenSslCAProvider(OPENSSL, new File(targetDir, CAROOT), PASSWORD);
    Certificate caCert = provider.getCACertificate();
    assertNotNull("Checking ca cert is not null", caCert);
    assertTrue("Checking certificate is an X.509 one", caCert instanceof X509Certificate);
    X509Certificate xcc = (X509Certificate) caCert;
    System.out.println(xcc.getSubjectX500Principal().getName());
    System.out.println(xcc.getIssuerX500Principal().getName());
}

From source file:org.globus.gsi.trustmanager.TrustedCertPathFinder.java

/**
 * Method that validates the provided cert path to find a trusted certificate in the certificate store.
 * <p/>/*from  w ww. j  a  v  a  2 s.c o m*/
 * For each certificate i in certPath, it is expected that the i+1 certificate is the issuer of the certificate
 * path. See CertPath.
 * <p/>
 * For each certificate i in certpath, validate signature of certificate i get issuer of certificate i get
 * certificate i+i ensure that the certificate i+1 is issuer of certificate i If not, throw an exception for
 * illegal argument validate signature of i+1 Throw exception if it does not validate check if i+1 is a trusted
 * certificate in the trust store. If so return certpath until i+1 If not, continue; If all certificates in the
 * certpath have been checked and none exisits in trust store, check if trust store has certificate of issuer of
 * last certificate in CertPath. If so, return certPath + trusted certificate from trust store If not, throw
 * an exception for lack of valid trust root.
 *
 * @param keyStore The key store containing CA trust root certificates
 * @param certPath The certpath from which to extract a valid cert path to a trusted certificate.
 * @return The valid CertPath.
 * @throws CertPathValidatorException If the CertPath is invalid.
 */
public static CertPath findTrustedCertPath(KeyStore keyStore, CertPath certPath)
        throws CertPathValidatorException {

    // This will be the cert path to return
    List<X509Certificate> trustedCertPath = new ArrayList<X509Certificate>();
    // This is the certs to validate
    List<? extends Certificate> certs = certPath.getCertificates();

    X509Certificate x509Certificate;
    int index = 0;
    int certsSize = certs.size();

    Certificate certificate = certs.get(index);
    if (!(certificate instanceof X509Certificate)) {
        throw new CertPathValidatorException(
                "Certificate of type " + X509Certificate.class.getName() + " required");
    }
    x509Certificate = (X509Certificate) certificate;

    while (index < certsSize) {
        CertPath finalCertPath = isTrustedCert(keyStore, x509Certificate, trustedCertPath);
        if (finalCertPath != null) {
            return finalCertPath;
        }

        if (index + 1 >= certsSize) {
            break;
        }

        index++;
        Certificate issuerCertificate = certs.get(index);
        x509Certificate = checkCertificate(trustedCertPath, x509Certificate, issuerCertificate);
    }

    X509CertSelector selector = new X509CertSelector();
    selector.setSubject(x509Certificate.getIssuerX500Principal());
    Collection<? extends Certificate> caCerts;
    try {
        caCerts = KeyStoreUtil.getTrustedCertificates(keyStore, selector);
    } catch (KeyStoreException e) {
        throw new CertPathValidatorException(e);
    }
    if (caCerts.size() < 1) {
        throw new CertPathValidatorException("No trusted path can be constructed");
    }

    boolean foundTrustRoot = false;

    for (Certificate caCert : caCerts) {
        if (!(caCert instanceof X509Certificate)) {
            logger.warn("Skipped a certificate: not an X509Certificate");
            continue;
        }
        try {
            trustedCertPath.add(checkCertificate(trustedCertPath, x509Certificate, caCert));
            // currently the caCert self-signature is not checked
            // to be consistent with the isTrustedCert() method
            foundTrustRoot = true;
            // we found a CA cert that signed the certificate
            // so we don't need to check any more
            break;
        } catch (CertPathValidatorException e) {
            // fine, just move on to check the next potential CA cert
            // after the loop we'll check whether any were successful
            logger.warn("Failed to validate signature of certificate with " + "subject DN '"
                    + x509Certificate.getSubjectDN() + "' against a CA certificate with issuer DN '"
                    + ((X509Certificate) caCert).getSubjectDN() + "'");
        }
    }

    if (!foundTrustRoot) {
        throw new CertPathValidatorException("No trusted path can be constructed");
    }

    try {
        CertificateFactory certFac = CertificateFactory.getInstance("X.509");
        return certFac.generateCertPath(trustedCertPath);
    } catch (CertificateException e) {
        throw new CertPathValidatorException("Error generating trusted certificate path", e);
    }
}

From source file:test.unit.be.fedict.eid.tsl.WeSignTest.java

@Test
public void testLoadWeSignTSL() throws Exception {
    // setup//from   www  .  j  av  a2 s .c  om
    Document tslDocument = TrustTestUtils.loadDocumentFromResource("WESIGN_TSL_ID001.xml");

    // operate
    TrustServiceList trustServiceList = TrustServiceListFactory.newInstance(tslDocument);

    // verify
    assertNotNull(trustServiceList);
    LOG.debug("scheme name: " + trustServiceList.getSchemeName());
    assertEquals("WP3 - TSL TEST SCHEME", trustServiceList.getSchemeName());

    List<TrustServiceProvider> trustServiceProviders = trustServiceList.getTrustServiceProviders();
    for (TrustServiceProvider trustServiceProvider : trustServiceProviders) {
        LOG.debug("\tTSP name: " + trustServiceProvider.getName());
        if (false == "Certipost NV - E-Trust, Citizen CA, Foreigner CA"
                .equals(trustServiceProvider.getName())) {
            continue;
        }
        List<TrustService> trustServices = trustServiceProvider.getTrustServices();
        for (TrustService trustService : trustServices) {
            LOG.debug("\t\tTS name: " + trustService.getName());
            X509Certificate caCertificate = trustService.getServiceDigitalIdentity();
            LOG.debug("\t\tCA Subject: " + caCertificate.getSubjectX500Principal());
            LOG.debug("\t\tCA Issuer: " + caCertificate.getIssuerX500Principal());
        }
    }
}

From source file:mitm.common.security.cms.SignerIdentifierImpl.java

@Override
public boolean match(X509Certificate certificate) throws IOException {
    if (certificate == null) {
        return false;
    }/*from  w w  w  . j av  a  2s. c om*/

    if (issuer != null && !issuer.equals(certificate.getIssuerX500Principal())) {
        return false;
    }

    if (serialNumber != null && !serialNumber.equals(certificate.getSerialNumber())) {
        return false;
    }

    if (subjectKeyIdentifier != null && !Arrays.equals(subjectKeyIdentifier,
            X509CertificateInspector.getSubjectKeyIdentifier(certificate))) {
        return false;
    }

    return true;
}

From source file:org.casbah.provider.openssl.OpenSslCAProviderTest.java

@Test
public void testSign() throws CertificateException, IOException, CAProviderException {

    rollbackPreviousTests();/*ww w. java  2  s .c  o m*/

    String csr = FileUtils.readFileToString(new File(targetDir, "/client/requests/03.csr"));
    OpenSslCAProvider provider = new OpenSslCAProvider(OPENSSL, new File(targetDir, CAROOT), PASSWORD);
    X509Certificate cert = provider.sign(csr);
    assertNotNull(cert);
    assertEquals(new BigInteger("03"), cert.getSerialNumber());
    System.out.println(cert.getIssuerX500Principal().getName());
}

From source file:net.solarnetwork.pki.bc.test.BCCertificateServiceTest.java

@Test
public void createCACertificate() throws Exception {
    X509Certificate cert = service.generateCertificationAuthorityCertificate(TEST_CA_DN, publicKey, privateKey);
    assertEquals("Is a CA", Integer.MAX_VALUE, cert.getBasicConstraints()); // should be a CA
    assertEquals("Self signed", cert.getIssuerX500Principal(), cert.getSubjectX500Principal());
}

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

private String getCrlUrl(X509Certificate childCertificate) {

    URI crlUri = CrlTrustLinker.getCrlUri(childCertificate);
    if (null == crlUri) {
        LOG.warn("No CRL uri for: " + childCertificate.getIssuerX500Principal().toString());
        return null;
    }//from   www  .j  a  va2s  .  c o  m
    try {
        return crlUri.toURL().toString();
    } catch (MalformedURLException e) {
        LOG.warn("malformed URL: " + e.getMessage(), e);
        return null;
    }
}

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  va2s.  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);
}