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.node.setup.test.DefaultSetupServiceTest.java

@Test
public void renewNetworkCertificate() throws Exception {
    SetupIdentityInfo info = new SetupIdentityInfo(1L, TEST_CONF_VALUE, TEST_SOLARIN_HOST, getHttpServerPort(),
            false, TEST_PW_VALUE);//from  w  w  w  . java 2s. c  o m
    expect(setupIdentityDao.getSetupIdentityInfo()).andReturn(info).atLeastOnce();
    replayAll();
    keystoreService.saveCACertificate(CA_CERT);
    keystoreService.generateNodeSelfSignedCertificate(TEST_DN);
    String csr = keystoreService.generateNodePKCS10CertificateRequestString();

    X509Certificate originalCert;

    PemReader pemReader = new PemReader(new StringReader(csr));
    try {
        PemObject pem = pemReader.readPemObject();
        PKCS10CertificationRequest req = new PKCS10CertificationRequest(pem.getContent());
        originalCert = PKITestUtils.sign(req, CA_CERT, CA_KEY_PAIR.getPrivate());
        String signedPem = PKITestUtils.getPKCS7Encoding(new X509Certificate[] { originalCert });
        keystoreService.saveNodeSignedCertificate(signedPem);

        log.debug("Saved signed node certificate {}:\n{}", originalCert.getSerialNumber(), signedPem);

        assertThat("Generated CSR", csr, notNullValue());
    } finally {
        pemReader.close();
    }

    // now let's renew!
    AbstractTestHandler handler = new AbstractTestHandler() {

        @Override
        protected boolean handleInternal(String target, HttpServletRequest request,
                HttpServletResponse response, int dispatch) throws Exception {
            assertEquals("POST", request.getMethod());
            assertEquals("/solarin/api/v1/sec/cert/renew", target);
            String password = request.getParameter("password");
            assertEquals("foobar", password);

            String keystoreData = request.getParameter("keystore");
            assertNotNull(keystoreData);
            byte[] data = Base64.decodeBase64(keystoreData);
            KeyStore keyStore = KeyStore.getInstance("pkcs12");
            keyStore.load(new ByteArrayInputStream(data), password.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());

            response.setContentType("application/json");
            PrintWriter out = response.getWriter();
            out.write("{\"success\":true}");
            out.flush();
            response.flushBuffer();
            return true;
        }

    };
    httpServer.addHandler(handler);

    service.renewNetworkCertificate("foobar");
}

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

public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData) {

    LOG.debug("certificate: " + childCertificate.getSubjectX500Principal());
    LOG.debug("certificate Issuer: " + childCertificate.getIssuerX500Principal().toString());

    LOG.debug("Issuer: " + certificate.getSubjectX500Principal());

    BigInteger issuerSerialNumber = certificate.getSerialNumber();
    String key = new String();
    key += certificate.getSubjectX500Principal().toString() + "|" + issuerSerialNumber.toString();

    String issuerName = childCertificate.getIssuerX500Principal().toString();

    CertificateAuthorityEntity certificateAuthority = this.entityManager
            //.find(CertificateAuthorityEntity.class, issuerName);
            .find(CertificateAuthorityEntity.class, key);
    if (null == certificateAuthority) {
        LOG.debug("no data cache entry for CA: " + issuerName + " - Serial Number: "
                + issuerSerialNumber.toString());
        /*//w  w w  .j  av  a2 s  .c  om
         * Cache Miss
         */
        SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);

        /*
         * Lookup Root CA's trust point via parent certificates' CA entity.
         */
        String parentIssuerName = certificate.getIssuerX500Principal().toString();
        CertificateAuthorityEntity parentCertificateAuthority = this.entityManager
                .find(CertificateAuthorityEntity.class, parentIssuerName);
        if (null == parentCertificateAuthority) {
            logAudit("CA not found for " + parentIssuerName);
            LOG.error("CA not found for " + parentIssuerName + " ?!");
            return null;
        }

        // create new CA
        try {
            certificateAuthority = new CertificateAuthorityEntity(getCrlUrl(childCertificate), certificate);
            certificateAuthority.setTrustPoint(parentCertificateAuthority.getTrustPoint());
        } catch (CertificateEncodingException e) {
            LOG.error("certificate encoding error: " + e.getMessage(), e);
            return null;
        }
        this.entityManager.persist(certificateAuthority);
        return null;
    }
    if (Status.ACTIVE != certificateAuthority.getStatus()) {
        LOG.debug("CA revocation data cache not yet active: " + issuerName);
        /*
         * Harvester is still busy processing the first CRL.
         */
        if (null == certificateAuthority.getCrlUrl()) {
            certificateAuthority.setCrlUrl(getCrlUrl(childCertificate));
        }

        if (Status.NONE != certificateAuthority.getStatus()) {
            // none means no CRL is available so not really a cache miss
            SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
        }
        return null;
    }
    /*
     * Let's use the cached revocation data
     */
    Date thisUpdate = certificateAuthority.getThisUpdate();
    if (null == thisUpdate) {
        LOG.warn("no thisUpdate value: " + certificateAuthority.getName());
        SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
        return null;
    }
    Date nextUpdate = certificateAuthority.getNextUpdate();
    if (null == nextUpdate) {
        LOG.warn("no nextUpdate value: " + certificateAuthority.getName());
        SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
        return null;
    }
    /*
     * First check whether the cached revocation data is up-to-date.
     */
    if (thisUpdate.after(validationDate)) {
        LOG.warn("cached CRL data too recent: " + certificateAuthority.getName());
        SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
        return null;
    }
    if (validationDate.after(nextUpdate)) {
        LOG.warn("cached CRL data too old: " + certificateAuthority.getName());
        SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
        return null;
    }
    LOG.debug("using cached CRL data");
    /*
     * Cache Hit
     */
    SNMPInterceptor.increment(SnmpConstants.CACHE_HITS, SnmpConstants.SNMP_SERVICE, 1L);

    BigInteger serialNumber = childCertificate.getSerialNumber();
    RevokedCertificateEntity revokedCertificate = findRevokedCertificate(issuerName, serialNumber);
    if (null == revokedCertificate) {
        LOG.debug("certificate valid: " + childCertificate.getSubjectX500Principal());
        return new TrustLinkerResult(true);
    }
    if (revokedCertificate.getRevocationDate().after(validationDate)) {
        LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal() + " at " + validationDate);
        return new TrustLinkerResult(true);
    }
    LOG.debug("certificate invalid: " + childCertificate.getSubjectX500Principal());
    return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
            "certificate revoked by cached CRL");
}

From source file:org.openanzo.client.AnzoTrustManager.java

private void handleCertificateException(CertificateException ce, X509Certificate[] chain)
        throws CertificateException {
    if (trustAll) {
        return;//from ww  w .  ja v  a  2 s  . c om
    }

    System.err.println(ce.getMessage());
    System.err.println("Certificate Information: \n");
    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(chain[0].getNotBefore().getTime());
    System.err.println("Creation Date: " + MONTHS[cal.get(Calendar.MONTH)] + " "
            + cal.get(Calendar.DAY_OF_MONTH) + ", " + cal.get(Calendar.YEAR));
    //System.err.println("Entry type: " + chain[0].getType());
    System.err.println("Certificate chain length: " + chain.length);

    // print some information about the certificate(s) that failed
    int i = 1;
    for (X509Certificate cert : chain) {
        System.err.println("Certificate[" + i++ + "]:");
        System.err.println("Owner: " + cert.getSubjectX500Principal().toString());
        System.err.println("Issuer: " + cert.getIssuerX500Principal().toString());

        String serialNum = new String(Hex.encodeHex(cert.getSerialNumber().toByteArray()));
        System.err.println("Serial Number: " + serialNum);
        System.err.println(
                "Valid from: " + cert.getNotBefore().toString() + " until: " + cert.getNotAfter().toString());
        System.err.println("Certificate fingerprints: ");
        try {
            byte[] sig = cert.getEncoded();
            System.err.println("\tMD5: " + getHash(sig, "MD5"));
            System.err.println("\tSHA1: " + getHash(sig, "SHA1"));
        } catch (NoSuchAlgorithmException e) {
        }
        System.err.println("\tSignature Algorithm Name: " + cert.getSigAlgName());
        System.err.println("\tVersion: " + cert.getVersion());
        System.err.println("-----------------------------------------------------");
    }
    System.err.println("Would you like to accept this certificate? (o)nce, (a)lways, (n)o");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line = "";
    try {
        line = in.readLine();
    } catch (IOException e) {
        CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
        System.exit(1);
    }
    if (Character.toLowerCase(line.charAt(0)) == 'o') {
        return;
    } else if (Character.toLowerCase(line.charAt(0)) == 'a') {
        try {
            String truststoreType = System.getProperty("javax.net.ssl.trustStoreType", "JCEKS");
            String truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_PWORD);

            String truststorePath = System.getProperty("javax.net.ssl.trustStore");
            if (truststorePath == null) { // there is no trust store location in the user's settings.trig file
                String userHome = System.getProperty("user.home");
                if (userHome == null)
                    throw new AnzoException(ExceptionConstants.CLIENT.FAILED_INITIALIZE_TRUST_MANAGER,
                            "User's home directory is not specified");
                File truststoreFile = new File(new File(userHome, ANZO_DIR), DEFAULT_CLIENT_TRUST);
                truststorePath = truststoreFile.getCanonicalPath();
                if (!truststoreFile.exists())
                    openTruststore(truststoreType, truststorePath, truststorePassword);
            } else {
                truststorePath = CommandContext.preprocessString(truststorePath);
                File truststoreFile = new File(truststorePath);

                if (!truststoreFile.exists()) {
                    System.err.println("Could not find the specified trust store file at:");
                    System.err.println(truststoreFile.getCanonicalPath());
                    System.err.println(
                            "The trust store file is used for permanently trusting server certificates that");
                    System.err.println("are not trusted by default.");
                    System.err.println(
                            "Would you like to create a new trust store file at the specified location?");
                    System.err.println("(y)es, (n)o");
                    try {
                        line = in.readLine();
                    } catch (IOException e) {
                        CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
                        System.exit(1);
                    }
                    if (Character.toLowerCase(line.charAt(0)) == 'y')
                        openTruststore(truststoreType, truststorePath, truststorePassword);
                    else
                        System.exit(1);
                }
            }

            KeystoreUtils.addTrustedCert(truststorePath, truststoreType, truststorePassword,
                    "imported_" + System.currentTimeMillis(), chain[0]);
        } catch (AnzoException ae) {
            System.err.println("Error importing certificate into truststore: ");
            CommandLineInterface.DEFAULT_CONSOLE.printException(ae, showTrace);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error importing certificate into truststore: ");
            CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
            System.exit(1);
        }
    } else {
        System.exit(1); // if the user does not want to trust the certificate then exit
    }
}

From source file:be.fedict.eid.applet.service.signer.time.TSPTimeStampService.java

public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
    // digest the message
    MessageDigest messageDigest = MessageDigest.getInstance(this.digestAlgo);
    byte[] digest = messageDigest.digest(data);

    // generate the TSP request
    BigInteger nonce = new BigInteger(128, new SecureRandom());
    TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
    requestGenerator.setCertReq(true);/*from  w w  w .  j a  v a  2 s  .c  o m*/
    if (null != this.requestPolicy) {
        requestGenerator.setReqPolicy(this.requestPolicy);
    }
    TimeStampRequest request = requestGenerator.generate(this.digestAlgoOid, digest, nonce);
    byte[] encodedRequest = request.getEncoded();

    // create the HTTP client
    HttpClient httpClient = new HttpClient();
    if (null != this.username) {
        Credentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    if (null != this.proxyHost) {
        httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort);
    }

    // create the HTTP POST request
    PostMethod postMethod = new PostMethod(this.tspServiceUrl);
    RequestEntity requestEntity = new ByteArrayRequestEntity(encodedRequest, "application/timestamp-query");
    postMethod.addRequestHeader("User-Agent", this.userAgent);
    postMethod.setRequestEntity(requestEntity);

    // invoke TSP service
    int statusCode = httpClient.executeMethod(postMethod);
    if (HttpStatus.SC_OK != statusCode) {
        LOG.error("Error contacting TSP server " + this.tspServiceUrl);
        throw new Exception("Error contacting TSP server " + this.tspServiceUrl);
    }

    // HTTP input validation
    Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type");
    if (null == responseContentTypeHeader) {
        throw new RuntimeException("missing Content-Type header");
    }
    String contentType = responseContentTypeHeader.getValue();
    if (!contentType.startsWith("application/timestamp-reply")) {
        LOG.debug("response content: " + postMethod.getResponseBodyAsString());
        throw new RuntimeException("invalid Content-Type: " + contentType);
    }
    if (0 == postMethod.getResponseContentLength()) {
        throw new RuntimeException("Content-Length is zero");
    }

    // TSP response parsing and validation
    InputStream inputStream = postMethod.getResponseBodyAsStream();
    TimeStampResponse timeStampResponse = new TimeStampResponse(inputStream);
    timeStampResponse.validate(request);

    if (0 != timeStampResponse.getStatus()) {
        LOG.debug("status: " + timeStampResponse.getStatus());
        LOG.debug("status string: " + timeStampResponse.getStatusString());
        PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
        if (null != failInfo) {
            LOG.debug("fail info int value: " + failInfo.intValue());
            if (PKIFailureInfo.unacceptedPolicy == failInfo.intValue()) {
                LOG.debug("unaccepted policy");
            }
        }
        throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
    }
    TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    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/applet/service/CA POLITICA SELLADO DE TIEMPO - COSTA RICA.crt");
    X509Certificate rootCA = loadCertificate("be/fedict/eid/applet/service/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);

    // verify TSP signer signature
    timeStampToken.validate(tspCertificateChain.get(0), BouncyCastleProvider.PROVIDER_NAME);

    // verify TSP signer certificate
    this.validator.validate(tspCertificateChain, revocationData);

    LOG.debug("time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());

    byte[] timestamp = timeStampToken.getEncoded();
    return timestamp;
}

From source file:test.unit.org.owasp.webscarab.util.SunCertificateUtilsTest.java

@Test
public void testSign() throws Exception {
    // setup//from  w  w  w  .j a v  a2  s.  c o  m
    KeyPair caKeyPair = generateKeyPair();
    KeyPair entityKeyPair = generateKeyPair();
    X500Principal subject = new X500Principal("CN=Test");
    PublicKey pubKey = entityKeyPair.getPublic();
    X500Principal issuer = new X500Principal("CN=CA");
    PublicKey caPubKey = caKeyPair.getPublic();
    PrivateKey caKey = caKeyPair.getPrivate();
    Date begin = new Date();
    Date ends = new Date(begin.getTime() + (long) 1000 * 60 * 60 * 24 * 30);
    BigInteger serialNo = BigInteger.valueOf(1234);
    JcaX509ExtensionUtils jxeu = new JcaX509ExtensionUtils();

    // operate
    X509Certificate resultCert = SunCertificateUtils.sign(subject, pubKey, issuer, caPubKey, caKey, begin, ends,
            serialNo, null);

    // verify
    assertNotNull(resultCert);
    LOG.debug("result certificate: " + resultCert);
    resultCert.verify(caPubKey);
    assertEquals(subject, resultCert.getSubjectX500Principal());
    assertEquals(issuer, resultCert.getIssuerX500Principal());
    assertEquals(serialNo, resultCert.getSerialNumber());
    assertEquals(pubKey, resultCert.getPublicKey());
    LOG.debug("expected begin: " + begin.getTime());
    LOG.debug("actual begin: " + resultCert.getNotBefore().getTime());
    /*
     * BouncyCastle drops the milliseconds.
     */
    assertTrue(Math.abs(begin.getTime() - resultCert.getNotBefore().getTime()) < 1000);
    assertTrue(Math.abs(ends.getTime() - resultCert.getNotAfter().getTime()) < 1000);

    byte[] subjectKeyIdentifierExtValue = resultCert
            .getExtensionValue(X509Extension.subjectKeyIdentifier.getId());
    assertNotNull(subjectKeyIdentifierExtValue);
    ASN1Primitive subjectKeyIdentifier = JcaX509ExtensionUtils
            .parseExtensionValue(subjectKeyIdentifierExtValue);
    ASN1Primitive expSKI = jxeu.createSubjectKeyIdentifier(pubKey).toASN1Primitive();
    assertArrayEquals(expSKI.getEncoded(), subjectKeyIdentifier.getEncoded());

    byte[] authorityKeyIdentifierExtValue = resultCert
            .getExtensionValue(X509Extension.authorityKeyIdentifier.getId());
    ASN1Primitive authorityKeyIdentifier = JcaX509ExtensionUtils
            .parseExtensionValue(authorityKeyIdentifierExtValue);
    ASN1Primitive expAKI = jxeu.createAuthorityKeyIdentifier(caPubKey).toASN1Primitive();
    assertArrayEquals(expAKI.getEncoded(), authorityKeyIdentifier.getEncoded());

    assertEquals(-1, resultCert.getBasicConstraints());

    byte[] netscapeCertTypeExtValue = resultCert
            .getExtensionValue(MiscObjectIdentifiers.netscapeCertType.getId());
    assertNotNull(netscapeCertTypeExtValue);
    DERBitString netscapeCertTypeExt = (DERBitString) X509ExtensionUtil
            .fromExtensionValue(netscapeCertTypeExtValue);
    NetscapeCertType netscapeCertType = new NetscapeCertType(netscapeCertTypeExt);
    assertEquals(NetscapeCertType.sslClient, netscapeCertType.intValue() & NetscapeCertType.sslClient);
    assertEquals(NetscapeCertType.sslServer, netscapeCertType.intValue() & NetscapeCertType.sslServer);

    assertTrue(resultCert.getKeyUsage()[0]);
    assertTrue(resultCert.getKeyUsage()[2]);

    byte[] extendedKeyUsageExtValue = resultCert.getExtensionValue(X509Extension.extendedKeyUsage.getId());
    assertNotNull(extendedKeyUsageExtValue);
    ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage
            .getInstance(X509ExtensionUtil.fromExtensionValue(extendedKeyUsageExtValue));
    assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth));
    assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth));
}

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;
    }/*www  .ja v  a2s . c  om*/

    // 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:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java

/**
 * Gets the issuer certificate./*w  ww  . j  a  va2s. c  o m*/
 *
 * @param certificates certs
 * @return issuer cert
 */
private X509Certificate getIssuerCertificate(final X509Certificate[] certificates) {
    if (certificates.length > 1) {
        return certificates[1];
    } else if (certificates.length == 1) {
        final X509Certificate subjectCertificate = getSubjectCertificate(certificates);
        final X500Principal issuerPrincipal = subjectCertificate.getIssuerX500Principal();
        return trustedCAs.get(issuerPrincipal.getName());
    } else {
        return null;
    }
}

From source file:org.apache.ws.security.validate.SignatureTrustValidator.java

/**
 * Evaluate whether a given certificate should be trusted.
 * /*  w w  w  . j av a 2s . c  o m*/
 * Policy used in this implementation:
 * 1. Search the keystore for the transmitted certificate
 * 2. Search the keystore for a connection to the transmitted certificate
 * (that is, search for certificate(s) of the issuer of the transmitted certificate
 * 3. Verify the trust path for those certificates found because the search for the issuer 
 * might be fooled by a phony DN (String!)
 *
 * @param cert the certificate that should be validated against the keystore
 * @param crypto A crypto instance to use for trust validation
 * @param data A RequestData instance
 * @param enableRevocation Whether revocation is enabled or not
 * @return true if the certificate is trusted, false if not
 * @throws WSSecurityException
 */
protected boolean verifyTrustInCert(X509Certificate cert, Crypto crypto, RequestData data,
        boolean enableRevocation) throws WSSecurityException {
    String subjectString = cert.getSubjectX500Principal().getName();
    String issuerString = cert.getIssuerX500Principal().getName();
    BigInteger issuerSerial = cert.getSerialNumber();

    if (LOG.isDebugEnabled()) {
        LOG.debug("Transmitted certificate has subject " + subjectString);
        LOG.debug("Transmitted certificate has issuer " + issuerString + " (serial " + issuerSerial + ")");
    }

    //
    // FIRST step - Search the keystore for the transmitted certificate
    //
    if (!enableRevocation && isCertificateInKeyStore(crypto, cert)) {
        return true;
    }

    //
    // SECOND step - Search for the issuer cert (chain) of the transmitted certificate in the 
    // keystore or the truststore
    //
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.SUBJECT_DN);
    cryptoType.setSubjectDN(issuerString);
    X509Certificate[] foundCerts = crypto.getX509Certificates(cryptoType);

    // If the certs have not been found, the issuer is not in the keystore/truststore
    // As a direct result, do not trust the transmitted certificate
    if (foundCerts == null || foundCerts.length < 1) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No certs found in keystore for issuer " + issuerString + " of certificate for "
                    + subjectString);
        }
        return false;
    }

    //
    // THIRD step
    // Check the certificate trust path for the issuer cert chain
    //
    if (LOG.isDebugEnabled()) {
        LOG.debug("Preparing to validate certificate path for issuer " + issuerString);
    }
    //
    // Form a certificate chain from the transmitted certificate
    // and the certificate(s) of the issuer from the keystore/truststore
    //
    X509Certificate[] x509certs = new X509Certificate[foundCerts.length + 1];
    x509certs[0] = cert;
    for (int j = 0; j < foundCerts.length; j++) {
        x509certs[j + 1] = (X509Certificate) foundCerts[j];
    }

    //
    // Use the validation method from the crypto to check whether the subjects' 
    // certificate was really signed by the issuer stated in the certificate
    //
    if (crypto.verifyTrust(x509certs, enableRevocation)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Certificate path has been verified for certificate with subject " + subjectString);
        }
        Collection<Pattern> subjectCertConstraints = data.getSubjectCertConstraints();
        if (matches(cert, subjectCertConstraints)) {
            return true;
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Certificate path could not be verified for certificate with subject " + subjectString);
    }
    return false;
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateManagementServiceImplTests.java

@Test(description = "This test case tests generation of a X509Certificate from a CSR")
public void testGenerateCertificateFromCSR() throws KeystoreException, IOException {
    CSRGenerator csrGeneration = new CSRGenerator();
    KeyStoreReader keyStoreReader = new KeyStoreReader();
    // Generate key pair
    KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024);
    byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair);
    PKCS10CertificationRequest certificationRequest;
    PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
    X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();
    certificationRequest = new PKCS10CertificationRequest(csrData);
    X509Certificate x509Certificate = managementService.generateCertificateFromCSR(privateKeyCA,
            certificationRequest, certCA.getIssuerX500Principal().getName());
    Assert.assertNotNull(x509Certificate);
    Assert.assertEquals(x509Certificate.getType(), CertificateManagementConstants.X_509);
    log.info("GenerateCertificateFromCSR Test Successful");
}

From source file:be.e_contract.mycarenet.etee.EncryptionToken.java

private X509Certificate parseEncryptionCertificate(byte[] encodedEncryptionToken)
        throws CMSException, CertificateException, IOException, OperatorCreationException {
    CMSSignedData cmsSignedData = new CMSSignedData(encodedEncryptionToken);

    // get signer identifier
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next();
    SignerId signerId = signer.getSID();

    // get signer certificate
    Store certificateStore = cmsSignedData.getCertificates();
    LOG.debug("certificate store type: " + certificateStore.getClass().getName());
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> signingCertificateCollection = certificateStore.getMatches(signerId);
    X509CertificateHolder signingCertificateHolder = signingCertificateCollection.iterator().next();
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate signingCertificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(signingCertificateHolder.getEncoded()));
    LOG.debug("signing certificate: " + signingCertificate.getSubjectX500Principal());

    // verify CMS signature
    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(signingCertificate);//  w w w  . ja  va  2  s .co  m
    boolean signatureResult = signer.verify(signerInformationVerifier);
    if (false == signatureResult) {
        throw new SecurityException("ETK signature invalid");
    }

    // get encryption certificate
    CMSTypedData signedContent = cmsSignedData.getSignedContent();
    byte[] data = (byte[]) signedContent.getContent();
    X509Certificate encryptionCertificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(data));

    LOG.debug("all available certificates:");
    logCertificates(certificateStore, null);

    // get authentication certificate
    CustomSelector authenticationSelector = new CustomSelector();
    authenticationSelector.setSubject(encryptionCertificate.getIssuerX500Principal());
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> authenticationCertificates = certificateStore
            .getMatches(authenticationSelector);
    if (authenticationCertificates.size() != 1) {
        LOG.debug("no authentication certificate match");
    }
    X509CertificateHolder authenticationCertificateHolder = authenticationCertificates.iterator().next();
    this.authenticationCertificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(authenticationCertificateHolder.getEncoded()));

    verifyProxyCertificate(encryptionCertificate, this.authenticationCertificate);

    return encryptionCertificate;
}