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:org.apache.hadoop.yarn.server.resourcemanager.security.TestX509SecurityHandler.java

@Test
public void testSuccessfulCertificateCreationTesting() throws Exception {
    File testSpecificSSLServerFile = null;
    try {//  w  w w.  jav a2s  .c om
        conf.set(YarnConfiguration.HOPS_RM_SECURITY_ACTOR_KEY,
                "org.apache.hadoop.yarn.server.resourcemanager.security.TestingRMAppSecurityActions");

        RMAppSecurityActions testActor = RMAppSecurityActionsFactory.getInstance().getActor(conf);
        String trustStore = Paths.get(BASE_DIR, "trustStore.jks").toString();
        X509Certificate caCert = ((TestingRMAppSecurityActions) testActor).getCaCert();
        String principal = caCert.getIssuerX500Principal().getName();
        // Principal should be CN=RootCA
        String alias = principal.split("=")[1];
        String password = "password";

        String sslServer = TestX509SecurityHandler.class.getSimpleName()
                + "-testSuccessfulCertificateCreationTesting.ssl-server.xml";
        testSpecificSSLServerFile = Paths.get(classPath, sslServer).toFile();

        conf.set(SSLFactory.SSL_SERVER_CONF_KEY, sslServer);

        createTrustStore(trustStore, password, alias, caCert);
        Configuration sslServerConf = createSSLConfig("", "", "", trustStore, password, "");
        saveConfig(testSpecificSSLServerFile.getAbsoluteFile(), sslServerConf);

        MockRMAppEventHandler eventHandler = new MockRMAppEventHandler(
                RMAppEventType.SECURITY_MATERIAL_GENERATED);
        rmContext.getDispatcher().register(RMAppEventType.class, eventHandler);

        RMAppSecurityManager rmAppSecurityManager = new RMAppSecurityManager(rmContext);
        X509SecurityHandler x509SecurityHandler = new MockX509SecurityHandler(rmContext, rmAppSecurityManager,
                true);
        rmAppSecurityManager.registerRMAppSecurityHandler(x509SecurityHandler);
        rmAppSecurityManager.init(conf);
        rmAppSecurityManager.start();
        ApplicationId appId = ApplicationId.newInstance(System.currentTimeMillis(), 1);
        X509SecurityHandler.X509MaterialParameter x509Param = new X509SecurityHandler.X509MaterialParameter(
                appId, "Dorothy", 1);
        RMAppSecurityMaterial securityMaterial = new RMAppSecurityMaterial();
        securityMaterial.addMaterial(x509Param);
        RMAppSecurityManagerEvent genSecurityMaterialEvent = new RMAppSecurityManagerEvent(appId,
                securityMaterial, RMAppSecurityManagerEventType.GENERATE_SECURITY_MATERIAL);

        rmAppSecurityManager.handle(genSecurityMaterialEvent);

        dispatcher.await();
        eventHandler.verifyEvent();
        rmAppSecurityManager.stop();
    } finally {
        if (testSpecificSSLServerFile != null) {
            testSpecificSSLServerFile.delete();
        }
    }
}

From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java

/**
 * Validates the specified certificate using OCSP if configured.
 *
 * @param certificates the client certificates
 * @throws CertificateStatusException ex
 *//*from  w w w . jav a  2s. c om*/
public void validate(final X509Certificate[] certificates) throws CertificateStatusException {
    // only validate if configured to do so
    if (client != null && certificates != null && certificates.length > 0) {
        final X509Certificate subjectCertificate = getSubjectCertificate(certificates);
        final X509Certificate issuerCertificate = getIssuerCertificate(certificates);
        if (issuerCertificate == null) {
            throw new IllegalArgumentException(String.format(
                    "Unable to obtain certificate of issuer <%s> for the specified subject certificate <%s>.",
                    subjectCertificate.getIssuerX500Principal().getName(),
                    subjectCertificate.getSubjectX500Principal().getName()));
        }

        // create the ocsp status key
        final OcspRequest ocspRequest = new OcspRequest(subjectCertificate, issuerCertificate);

        try {
            // determine the status and ensure it isn't verified as revoked
            final OcspStatus ocspStatus = ocspCache.getUnchecked(ocspRequest);

            // we only disallow when we have a verified response that states the certificate is revoked
            if (VerificationStatus.Verified.equals(ocspStatus.getVerificationStatus())
                    && ValidationStatus.Revoked.equals(ocspStatus.getValidationStatus())) {
                throw new CertificateStatusException(String.format(
                        "Client certificate for <%s> is revoked according to the certificate authority.",
                        subjectCertificate.getSubjectX500Principal().getName()));
            }
        } catch (final UncheckedExecutionException uee) {
            logger.warn(String.format("Unable to validate client certificate via OCSP: <%s>",
                    subjectCertificate.getSubjectX500Principal().getName()), uee.getCause());
        }
    }
}

From source file:org.apache.nifi.toolkit.tls.util.TlsHelperTest.java

@Test
public void testGenerateSelfSignedCert()
        throws GeneralSecurityException, IOException, OperatorCreationException {
    String dn = "CN=testDN,O=testOrg";

    X509Certificate x509Certificate = CertificateUtils.generateSelfSignedX509Certificate(
            TlsHelper.generateKeyPair(keyPairAlgorithm, keySize), dn, signingAlgorithm, days);

    Date notAfter = x509Certificate.getNotAfter();
    assertTrue(notAfter.after(inFuture(days - 1)));
    assertTrue(notAfter.before(inFuture(days + 1)));

    Date notBefore = x509Certificate.getNotBefore();
    assertTrue(notBefore.after(inFuture(-1)));
    assertTrue(notBefore.before(inFuture(1)));

    assertEquals(dn, x509Certificate.getIssuerX500Principal().getName());
    assertEquals(signingAlgorithm, x509Certificate.getSigAlgName());
    assertEquals(keyPairAlgorithm, x509Certificate.getPublicKey().getAlgorithm());

    x509Certificate.checkValidity();
}

From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java

@Override
public X509Certificate getSigningCertificate() {
    try {//from   w ww . j a  v  a2s . c om
        NodeList list = XMLUtils.getNodeList(signatureElement,
                "./ds:Object/xades:QualifyingProperties/xades:SignedProperties/xades:SignedSignatureProperties/"
                        + "xades:SigningCertificate/xades:Cert");

        for (int i = 0; i < list.getLength(); i++) {
            Element el = (Element) list.item(i);
            Element issuerSubjectNameEl = XMLUtils.getElement(el, "./xades:IssuerSerial/ds:X509IssuerName");
            X500Name issuerName = new X500Name(issuerSubjectNameEl.getTextContent());
            for (X509Certificate c : getCertificateSource().getCertificates()) {
                X500Name cIssuer = new X500Name(c.getIssuerX500Principal().getName());
                if (cIssuer.equals(issuerName)) {
                    return c;
                }
            }
        }

        return null;
    } catch (XPathExpressionException e) {
        throw new EncodingException(MSG.SIGNING_CERTIFICATE_ENCODING);
    }
}

From source file:org.tolven.config.model.CredentialManager.java

private X509Certificate signCertificate(CertificateDetail certDetail, X500Principal subjectX500Principal,
        PublicKey subjectPublicKey) throws IOException, GeneralSecurityException {
    CertificateGroupDetail caCertGroupDetail = getTolvenConfigWrapper()
            .getCredentialGroup(certDetail.getCaRefId());
    CertificateKeyDetail caKeyDetail = caCertGroupDetail.getKey();
    char[] caKeyPass = getPasswordHolder().getPassword(caCertGroupDetail.getId());
    PrivateKey caPrivateKey = getPrivateKey(caKeyDetail, caKeyPass);
    X509Certificate caCertificate = getTolvenConfigWrapper().getX509Certificate(caCertGroupDetail);
    return signCertificate(subjectX500Principal, subjectPublicKey, caCertificate.getIssuerX500Principal(),
            caPrivateKey);//  w  ww.j  a v a2  s.  c om
}

From source file:org.jscep.client.Client.java

public EnrollmentResponse poll(final X509Certificate identity, final PrivateKey identityKey,
        final X500Principal subject, final TransactionId transId, final String profile)
        throws ClientException, TransactionException {
    final Transport transport = createTransport(profile);
    CertStore store = getCaCertificate(profile);
    CertStoreInspector certStore = inspectorFactory.getInstance(store);
    X509Certificate issuer = certStore.getIssuer();

    PkiMessageEncoder encoder = getEncoder(identity, identityKey, profile);
    PkiMessageDecoder decoder = getDecoder(identity, identityKey, profile);

    IssuerAndSubject ias = new IssuerAndSubject(X500Utils.toX500Name(issuer.getIssuerX500Principal()),
            X500Utils.toX500Name(subject));

    final EnrollmentTransaction trans = new EnrollmentTransaction(transport, encoder, decoder, ias, transId);
    return send(trans);
}

From source file:org.dataone.proto.trove.net.SocketFactoryManager.java

/**
 * Load PEM file contents into in-memory keystore NOTE: this implementation uses Bouncy Castle security provider
 *
 * @return the keystore that will provide the material
 * @throws KeyStoreException/*w  ww.  ja  v a2  s  .c om*/
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
private KeyStore getKeyStore()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

    // if the location has been set, use it
    KeyStore keyStore = null;
    Object pemObject = null;

    keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, keyStorePassword.toCharArray());

    // get the private key and certificate from the PEM
    // TODO: find a way to do this with default Java provider (not Bouncy Castle)?
    Security.addProvider(new BouncyCastleProvider());
    PEMParser pemReader = new PEMParser(new FileReader(clientCertificateLocation));

    X509Certificate certificate = null;
    PrivateKey privateKey = null;
    KeyPair keyPair = null;

    while ((pemObject = pemReader.readObject()) != null) {
        if (pemObject instanceof PrivateKey) {
            privateKey = (PrivateKey) pemObject;
        } else if (pemObject instanceof KeyPair) {
            keyPair = (KeyPair) pemObject;
            privateKey = keyPair.getPrivate();
        } else if (pemObject instanceof X509Certificate) {
            certificate = (X509Certificate) pemObject;
        }
    }
    if (certificate == null) {
        log.warn("Certificate is null");
    } else {
        if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253)
                .equals(certificate.getIssuerX500Principal().getName(X500Principal.RFC2253))) {
            log.warn("Certificate is Self Signed");
        }
    }
    Certificate[] chain = new Certificate[] { certificate };

    // set the entry
    keyStore.setKeyEntry("cilogon", privateKey, keyStorePassword.toCharArray(), chain);

    return keyStore;

}

From source file:org.apache.ws.security.components.crypto.CryptoBase.java

private String getAliasForX509Cert(String issuer, BigInteger serialNumber, boolean useSerialNumber)
        throws WSSecurityException {
    Object issuerName = null;//w  w  w. ja  va 2 s.  c o m
    Certificate cert = null;

    if (keystore == null) {
        return null;
    }

    //
    // Convert the issuer DN to a java X500Principal object first. This is to ensure
    // interop with a DN constructed from .NET, where e.g. it uses "S" instead of "ST".
    // Then convert it to a BouncyCastle X509Name, which will order the attributes of
    // the DN in a particular way (see WSS-168). If the conversion to an X500Principal
    // object fails (e.g. if the DN contains "E" instead of "EMAILADDRESS"), then fall
    // back on a direct conversion to a BC X509Name
    //
    try {
        X500Principal issuerRDN = new X500Principal(issuer);
        issuerName = createBCX509Name(issuerRDN.getName());
    } catch (java.lang.IllegalArgumentException ex) {
        issuerName = createBCX509Name(issuer);
    }

    try {
        for (Enumeration e = keystore.aliases(); e.hasMoreElements();) {
            String alias = (String) e.nextElement();
            Certificate[] certs = keystore.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = keystore.getCertificate(alias);
                if (cert == null) {
                    continue;
                }
            } else {
                cert = certs[0];
            }
            if (!(cert instanceof X509Certificate)) {
                continue;
            }
            X509Certificate x509cert = (X509Certificate) cert;
            if (!useSerialNumber || x509cert.getSerialNumber().compareTo(serialNumber) == 0) {
                Object certName = createBCX509Name(x509cert.getIssuerX500Principal().getName());
                if (certName.equals(issuerName)) {
                    return alias;
                }
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e);
    }
    return null;
}

From source file:net.sf.dsig.DSApplet.java

private Map<String, X509Certificate[]> createAliasX509CertificateChainPair(KeyStoreProxy ksh)
        throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
    Map<String, X509Certificate[]> aliasX509CertificateChainPair = new HashMap<String, X509Certificate[]>();

    Set<String> aliases = ksh.aliases();
    for (String alias : aliases) {
        X509Certificate[] certificateChain = ksh.getX509CertificateChain(alias);
        if (certificateChain == null || certificateChain.length == 0) {
            logger.warn("Null certificate chain returned; alias=" + alias);

            continue;
        }//w  ww  .  j  a  va 2s .  co m

        X509Certificate certificate = certificateChain[0];

        String subjectName = certificate.getSubjectX500Principal().getName();
        String issuerName = certificate.getIssuerX500Principal().getName();
        BigInteger serialNumber = certificate.getSerialNumber();

        // Filter by subject

        if (getSubjectMatchingPattern() != null
                && !getSubjectMatchingPattern().matcher(subjectName).matches()) {
            logger.info("Subject does not match; skipping" + ": certificate.subject=" + subjectName);
            continue;
        }

        // Filter by issuer

        if (getIssuerMatchingPattern() != null && !getIssuerMatchingPattern().matcher(issuerName).matches()) {
            logger.info("Issuer does not match; skipping" + ": certificate.subject=" + subjectName
                    + ", certificate.issuer=" + issuerName);
            continue;
        }

        // Filter by serial number

        if (getSerialNumbersAllowedSet() != null && !getSerialNumbersAllowedSet().contains(serialNumber)) {
            logger.info("Serial number is not allowed; skipping" + ": certificate.subject=" + subjectName
                    + ", certificate.serialNumber=" + serialNumber);
            continue;
        }

        // Filter by key usage

        if (keyUsageRestrictions != null
                && !KeyUsageHelper.validateKeyUsage(certificate, keyUsageRestrictions)) {
            logger.info("Key usage restrictions not met; skipping" + ": certificate.subject=" + subjectName
                    + ", certificate.keyUsage=" + KeyUsageHelper.printKeyUsage(certificate));
            continue;
        }

        // Filter by private key

        if (!ksh.isKeyEntry(alias)) {
            logger.info("Private key not found; skipping" + ": certificate.subject=" + subjectName);
            continue;
        }

        logger.debug("Accepting certificate" + "; certificate.alias=" + alias + ", certificate.subject="
                + subjectName + ", certificate.serialNumber=" + serialNumber);

        aliasX509CertificateChainPair.put(alias, ksh.getX509CertificateChain(alias));
    }

    return aliasX509CertificateChainPair;
}

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

/**
 * This method is used to retrieve signed certificate from certificate signing request.
 *
 * @param binarySecurityToken CSR that comes from the client as a String value.It is base 64 encoded request
 *                            security token.
 * @return Return signed certificate in X508Certificate type object.
 * @throws KeystoreException/*from   w  ww. j  a  v  a  2 s.c o  m*/
 */
public X509Certificate getSignedCertificateFromCSR(String binarySecurityToken) throws KeystoreException {
    byte[] byteArrayBst = DatatypeConverter.parseBase64Binary(binarySecurityToken);
    PKCS10CertificationRequest certificationRequest;
    KeyStoreReader keyStoreReader = new KeyStoreReader();
    PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
    X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();

    try {
        certificationRequest = new PKCS10CertificationRequest(byteArrayBst);
    } catch (IOException e) {
        throw new KeystoreException("CSR cannot be recovered.", e);
    }
    return generateCertificateFromCSR(privateKeyCA, certificationRequest,
            certCA.getIssuerX500Principal().getName());
}