Example usage for java.security.cert X509Certificate getSubjectX500Principal

List of usage examples for java.security.cert X509Certificate getSubjectX500Principal

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getSubjectX500Principal.

Prototype

public X500Principal getSubjectX500Principal() 

Source Link

Document

Returns the subject (subject distinguished name) value from the certificate as an X500Principal .

Usage

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

/**
 * Check to see if the certificate argument is in the keystore
 * @param crypto A Crypto instance to use for trust validation
 * @param cert The certificate to check/*from w  w  w.  j a  v  a  2  s  .  c om*/
 * @return true if cert is in the keystore
 * @throws WSSecurityException
 */
protected boolean isCertificateInKeyStore(Crypto crypto, X509Certificate cert) throws WSSecurityException {
    String issuerString = cert.getIssuerX500Principal().getName();
    BigInteger issuerSerial = cert.getSerialNumber();

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ISSUER_SERIAL);
    cryptoType.setIssuerSerial(issuerString, issuerSerial);
    X509Certificate[] foundCerts = crypto.getX509Certificates(cryptoType);

    //
    // If a certificate has been found, the certificates must be compared
    // to ensure against phony DNs (compare encoded form including signature)
    //
    if (foundCerts != null && foundCerts[0] != null && foundCerts[0].equals(cert)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Direct trust for certificate with " + cert.getSubjectX500Principal().getName());
        }
        return true;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("No certificate found for subject from issuer with " + issuerString + " (serial "
                + issuerSerial + ")");
    }
    return false;
}

From source file:org.nimbustools.ctxbroker.security.DefaultBootstrapFactory.java

public BootstrapInformation newBootstrap(String uuid, String ctxServiceURL, Calendar expires)
        throws ContextBrokerException {

    BootstrapInformation bootstrap = new BootstrapInformation();

    KeyPair keypair = this.ca.createNewKeyPair();

    X509Certificate cert;
    try {/*from w  ww . ja  va2s .  c o m*/
        cert = this.ca.signNewCertificate(uuid, keypair.getPublic(), expires);
    } catch (SignatureException e) {
        throw new ContextBrokerException(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        throw new ContextBrokerException(e.getMessage(), e);
    } catch (CertificateException e) {
        throw new ContextBrokerException(e.getMessage(), e);
    } catch (IOException e) {
        throw new ContextBrokerException(e.getMessage(), e);
    }

    try {
        bootstrap.setX509Cert(cert);
    } catch (CertificateEncodingException e) {
        throw new ContextBrokerException(e.getMessage(), e);
    }
    try {
        bootstrap.setKeypair(keypair);
    } catch (IOException e) {
        throw new ContextBrokerException(e.getMessage(), e);
    }

    X500Principal subjectDN = cert.getSubjectX500Principal();
    String DN = subjectDN.getName(X500Principal.RFC2253);
    String globusDN = CertUtil.toGlobusID(DN, false);
    bootstrap.setBootstrapDN(globusDN);

    return bootstrap;
}

From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java

private X509Certificate findCertIssuerInStore(X509Certificate x509cert, KeyStore kStore)
        throws CertificateException {
    X509Certificate x509issuer = null;

    debug("searching store for issuer: " + x509cert.getIssuerDN());

    // check in our local root CA Store
    Enumeration<String> enumAliases;
    try {//from w  w w  . j a va  2  s.c  o  m
        enumAliases = kStore.aliases();
        X509Certificate x509search = null;
        while (enumAliases.hasMoreElements()) {
            x509search = (X509Certificate) kStore.getCertificate(enumAliases.nextElement());

            if (checkSubjectMatchesIssuer(x509search.getSubjectX500Principal(),
                    x509cert.getIssuerX500Principal())) {
                x509issuer = x509search;
                debug("found issuer for current cert in chain in ROOT CA store: " + x509issuer.getSubjectDN());

                break;
            }
        }
    } catch (KeyStoreException e) {

        String errMsg = mContext.getString(R.string.error_problem_access_local_root_ca_store);
        debug(errMsg);

        throw new CertificateException(errMsg);
    }

    return x509issuer;
}

From source file:org.nimbustools.ctxbroker.security.CertificateAuthority.java

/**
 * CertificateAuthority constructor/* w w w. j  ava  2  s .  co m*/
 *
 * @param caCert CA's public cert, X509Certificate
 * @param caPrivateKey (unencrypted) private key object
 * @param globusCADN only used for logging
 * @throws NoSuchProviderException problem initializing keypair generator
 * @throws NoSuchAlgorithmException problem initializing keypair generator
 * @throws CertificateException problem initializing certificate factory
 * @throws IOException file/stream problem
 * @throws ContextBrokerException other problem with CA input
 */
protected CertificateAuthority(X509Certificate caCert, PrivateKey caPrivateKey, String globusCADN)
        throws NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException,
        ContextBrokerException {

    if (caCert == null) {
        throw new IllegalArgumentException("caCert is null");
    }

    if (caPrivateKey == null) {
        throw new IllegalArgumentException("caPrivateKey is null");
    }

    this.kpGen = KeyPairGenerator.getInstance("RSA", "BC");
    this.kpGen.initialize(1024, new SecureRandom());

    this.certGen = new X509V3CertificateGenerator();

    this.factory = CertificateFactory.getInstance("X.509", "BC");

    this.caX509 = caCert;
    this.caPrivate = caPrivateKey;

    this.caX509Name = new X509Principal(caX509.getIssuerX500Principal().getEncoded());

    this.initializeGenerator();

    X500Principal subjectDN = caCert.getSubjectX500Principal();

    String targetBase = subjectDN.getName(X500Principal.RFC2253);

    String[] parts = targetBase.split(",");
    String target = "";
    int cnCount = 0;
    for (int i = 0; i < parts.length; i++) {
        String newpiece;
        if (parts[i].startsWith("CN") || parts[i].startsWith("cn")) {
            newpiece = replaceToken;
            cnCount += 1;
        } else {
            newpiece = parts[i];
        }
        if (i == 0) {
            target = newpiece;
        } else {
            target = newpiece + "," + target;
        }
    }

    if (cnCount == 0) {
        throw new ContextBrokerException("Unsupported: CA has no " + "CN (?)");
    }

    if (cnCount != 1) {
        throw new ContextBrokerException("Unsupported: CA has more " + "than one CN");
    }

    this.targetString = target;

    final String msg = "Initialized certificate authority with subject " + "DN (RFC2253) = '" + targetBase
            + "' " + "and Globus style DN = '" + globusCADN + "'. " + "New DNs will look like this (RFC2253): '"
            + this.targetString + "'";

    logger.info(msg);
}

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

/**
 * Sends a CSR to the SCEP server for enrolling in a PKI.
 * <p>//from www  .j ava  2 s  .com
 * This method enrols the provider <tt>CertificationRequest</tt> into the
 * PKI represented by the SCEP server.
 *
 * @param identity
 *            the identity of the client.
 * @param key
 *            the private key to sign the SCEP request.
 * @param csr
 *            the CSR to enrol.
 * @param profile
 *            the SCEP server profile.
 * @return the certificate store returned by the server.
 * @throws ClientException
 *             if any client error occurs.
 * @throws TransactionException
 *             if there is a problem with the SCEP transaction.
 * @see CertStoreInspector
 */
public EnrollmentResponse enrol(final X509Certificate identity, final PrivateKey key,
        final PKCS10CertificationRequest csr, final String profile)
        throws ClientException, TransactionException {
    LOGGER.debug("Enrolling certificate with CA");

    if (isSelfSigned(identity)) {
        LOGGER.debug("Certificate is self-signed");
        X500Name csrSubject = csr.getSubject();
        X500Name idSubject = X500Utils.toX500Name(identity.getSubjectX500Principal());

        if (!csrSubject.equals(idSubject)) {
            LOGGER.error(
                    "The self-signed certificate MUST use the same subject name as in the PKCS#10 request.");
        }
    }
    // TRANSACTIONAL
    // Certificate enrollment
    final Transport transport = createTransport(profile);
    PkiMessageEncoder encoder = getEncoder(identity, key, profile);
    PkiMessageDecoder decoder = getDecoder(identity, key, profile);
    final EnrollmentTransaction trans = new EnrollmentTransaction(transport, encoder, decoder, csr);

    try {
        MessageDigest digest = getCaCapabilities(profile).getStrongestMessageDigest();
        byte[] hash = digest.digest(csr.getEncoded());

        LOGGER.debug("{} PKCS#10 Fingerprint: [{}]", digest.getAlgorithm(), Hex.encodeHexString(hash));
    } catch (IOException e) {
        LOGGER.error("Error getting encoded CSR", e);
    }

    return send(trans);
}

From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.DefaultHostnameVerifier.java

public final void verify(final String host, final X509Certificate cert) throws SSLException {
    final boolean ipv4 = InetAddressUtils.isIPv4Address(host);
    final boolean ipv6 = InetAddressUtils.isIPv6Address(host);
    final int subjectType = ipv4 || ipv6 ? IP_ADDRESS_TYPE : DNS_NAME_TYPE;
    final List<String> subjectAlts = extractSubjectAlts(cert, subjectType);
    if (subjectAlts != null && !subjectAlts.isEmpty()) {
        if (ipv4) {
            matchIPAddress(host, subjectAlts);
        } else if (ipv6) {
            matchIPv6Address(host, subjectAlts);
        } else {//from  w  ww  . j av a2  s  .  c om
            matchDNSName(host, subjectAlts, this.publicSuffixMatcher);
        }
    } else {
        // CN matching has been deprecated by rfc2818 and can be used
        // as fallback only when no subjectAlts are available
        final X500Principal subjectPrincipal = cert.getSubjectX500Principal();
        final String cn = extractCN(subjectPrincipal.getName(X500Principal.RFC2253));
        if (cn == null) {
            throw new SSLException("Certificate subject for <" + host + "> doesn't contain "
                    + "a common name and does not have alternative names");
        }
        matchCN(host, cn, this.publicSuffixMatcher);
    }
}

From source file:cybervillains.ca.KeyStoreManager.java

/**
 * This method returns the duplicated certificate mapped to the passed in cert, or
 * creates and returns one if no mapping has yet been performed.  If a naked public
 * key has already been mapped that matches the key in the cert, the already mapped
 * keypair will be reused for the mapped cert.
 * @param cert/*www  . j  av  a 2 s  .co  m*/
 * @return
 * @throws CertificateEncodingException
 * @throws InvalidKeyException
 * @throws CertificateException
 * @throws CertificateNotYetValidException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws SignatureException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 */
public synchronized X509Certificate getMappedCertificate(final X509Certificate cert)
        throws CertificateEncodingException, InvalidKeyException, CertificateException,
        CertificateNotYetValidException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException,
        KeyStoreException, UnrecoverableKeyException {

    String thumbprint = ThumbprintUtil.getThumbprint(cert);

    String mappedCertThumbprint = _certMap.get(thumbprint);

    if (mappedCertThumbprint == null) {

        // Check if we've already mapped this public key from a KeyValue
        PublicKey mappedPk = getMappedPublicKey(cert.getPublicKey());
        PrivateKey privKey;

        if (mappedPk == null) {
            PublicKey pk = cert.getPublicKey();

            String algo = pk.getAlgorithm();

            KeyPair kp;

            if (algo.equals("RSA")) {
                kp = getRSAKeyPair();
            } else if (algo.equals("DSA")) {
                kp = getDSAKeyPair();
            } else {
                throw new InvalidKeyException("Key algorithm " + algo + " not supported.");
            }
            mappedPk = kp.getPublic();
            privKey = kp.getPrivate();

            mapPublicKeys(cert.getPublicKey(), mappedPk);
        } else {
            privKey = getPrivateKey(mappedPk);
        }

        X509Certificate replacementCert = CertificateCreator.mitmDuplicateCertificate(cert, mappedPk,
                getSigningCert(), getSigningPrivateKey());

        addCertAndPrivateKey(null, replacementCert, privKey);

        mappedCertThumbprint = ThumbprintUtil.getThumbprint(replacementCert);

        _certMap.put(thumbprint, mappedCertThumbprint);
        _certMap.put(mappedCertThumbprint, thumbprint);
        _subjectMap.put(replacementCert.getSubjectX500Principal().getName(), thumbprint);

        if (persistImmediately) {
            persist();
        }
        return replacementCert;
    }
    return getCertificateByAlias(mappedCertThumbprint);

}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

private void validatePem(CertificateBundle certificateBundle, String subjectName)
        throws CertificateException, IOException, KeyVaultErrorException, IllegalArgumentException,
        InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException,
        IllegalBlockSizeException, BadPaddingException {
    // Load the CER part into X509Certificate object
    X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle);

    Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName));
    Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName));

    // Retrieve the secret backing the certificate
    SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier();
    SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier());
    Assert.assertTrue(secret.managed());
    String secretValue = secret.value();

    // Extract private key from PEM
    PrivateKey secretPrivateKey = extractPrivateKeyFromPemContents(secretValue);
    Assert.assertNotNull(secretPrivateKey);

    // Extract certificates from PEM
    List<X509Certificate> certificates = extractCertificatesFromPemContents(secretValue);
    Assert.assertNotNull(certificates);//from w  w w .j  a v  a2s  .  c om
    Assert.assertTrue(certificates.size() == 1);

    // has the public key corresponding to the private key.
    X509Certificate secretCertificate = certificates.get(0);
    Assert.assertNotNull(secretCertificate);
    Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName()
            .equals(x509Certificate.getSubjectX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName()
            .equals(x509Certificate.getIssuerX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber()));

    // Create a KeyPair with the private key from the KeyStore and public
    // key from the certificate to verify they match
    KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey);
    Assert.assertNotNull(keyPair);
    verifyRSAKeyPair(keyPair);
}

From source file:io.fabric8.kubernetes.api.KubernetesFactory.java

private void configureClientCert(WebClient webClient) {
    try (InputStream certInputStream = getInputStreamFromDataOrFile(clientCertData, clientCertFile)) {
        CertificateFactory certFactory = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

        InputStream keyInputStream = getInputStreamFromDataOrFile(clientKeyData, clientKeyFile);
        PEMReader reader = new PEMReader(keyInputStream);
        RSAPrivateCrtKeySpec keySpec = new PKCS1EncodedKeySpec(reader.getDerBytes()).getKeySpec();
        KeyFactory kf = KeyFactory.getInstance(clientKeyAlgo);
        RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null);/*  w w  w .  j  a  va  2 s.  com*/

        String alias = cert.getSubjectX500Principal().getName();
        keyStore.setKeyEntry(alias, privKey, clientKeyPassword, new Certificate[] { cert });

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, clientKeyPassword);

        HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit();

        TLSClientParameters params = conduit.getTlsClientParameters();

        if (params == null) {
            params = new TLSClientParameters();
            conduit.setTlsClientParameters(params);
        }

        KeyManager[] existingKeyManagers = params.getKeyManagers();
        KeyManager[] keyManagers;

        if (existingKeyManagers == null || ArrayUtils.isEmpty(existingKeyManagers)) {
            keyManagers = keyManagerFactory.getKeyManagers();
        } else {
            keyManagers = (KeyManager[]) ArrayUtils.addAll(existingKeyManagers,
                    keyManagerFactory.getKeyManagers());
        }

        params.setKeyManagers(keyManagers);

    } catch (Exception e) {
        log.error("Could not create key manager for " + clientCertFile + " (" + clientKeyFile + ")", e);
    }
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

/**
 * Import a PKCS12 format (which includes the private key) certificate.
 *//*from   www  . j a  va  2s .c o m*/
@Test
public void importCertificatePkcs12() throws Exception {
    String certificateContent = "MIIJOwIBAzCCCPcGCSqGSIb3DQEHAaCCCOgEggjkMIII4DCCBgkGCSqGSIb3DQEHAaCCBfoEggX2MIIF8jCCBe4GCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAj15YH9pOE58AICB9AEggTYLrI+SAru2dBZRQRlJY7XQ3LeLkah2FcRR3dATDshZ2h0IA2oBrkQIdsLyAAWZ32qYR1qkWxLHn9AqXgu27AEbOk35+pITZaiy63YYBkkpR+pDdngZt19Z0PWrGwHEq5z6BHS2GLyyN8SSOCbdzCz7blj3+7IZYoMj4WOPgOm/tQ6U44SFWek46QwN2zeA4i97v7ftNNns27ms52jqfhOvTA9c/wyfZKAY4aKJfYYUmycKjnnRl012ldS2lOkASFt+lu4QCa72IY6ePtRudPCvmzRv2pkLYS6z3cI7omT8nHP3DymNOqLbFqr5O2M1ZYaLC63Q3xt3eVvbcPh3N08D1hHkhz/KDTvkRAQpvrW8ISKmgDdmzN55Pe55xHfSWGB7gPw8sZea57IxFzWHTK2yvTslooWoosmGxanYY2IG/no3EbPOWDKjPZ4ilYJe5JJ2immlxPz+2e2EOCKpDI+7fzQcRz3PTd3BK+budZ8aXX8aW/lOgKS8WmxZoKnOJBNWeTNWQFugmktXfdPHAdxMhjUXqeGQd8wTvZ4EzQNNafovwkI7IV/ZYoa++RGofVR3ZbRSiBNF6TDj/qXFt0wN/CQnsGAmQAGNiN+D4mY7i25dtTu/Jc7OxLdhAUFpHyJpyrYWLfvOiS5WYBeEDHkiPUa/8eZSPA3MXWZR1RiuDvuNqMjct1SSwdXADTtF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CFd5VT2Rw5zDNrA/J3F5fMCk4wOzAfMAcGBSsOAwIaBBSxgh2xyF+88V4vAffBmZXv8Txt4AQU4O/NX4MjxSodbE7ApNAMIvrtREwCAgfQ";
    String certificatePassword = "123";

    // Set content type to indicate the certificate is PKCS12 format.
    SecretProperties secretProperties = new SecretProperties().withContentType(MIME_PKCS12);
    CertificatePolicy certificatePolicy = new CertificatePolicy().withSecretProperties(secretProperties);
    Attributes attribute = new CertificateAttributes().withEnabled(true);

    String vaultUri = getVaultUri();
    String certificateName = "importCertPkcs";
    CertificateBundle certificateBundle = keyVaultClient.importCertificate(
            new ImportCertificateRequest.Builder(vaultUri, certificateName, certificateContent)
                    .withPassword(certificatePassword).withPolicy(certificatePolicy).withAttributes(attribute)
                    .withTags(sTags).build());

    // Validate the certificate bundle created
    validateCertificateBundle(certificateBundle, certificatePolicy);
    Assert.assertTrue(toHexString(certificateBundle.x509Thumbprint())
            .equalsIgnoreCase("7cb8b7539d87ba7215357b9b9049dff2d3fa59ba"));
    Assert.assertEquals(attribute.enabled(), certificateBundle.attributes().enabled());

    // Load the CER part into X509Certificate object
    X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle);

    Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals("CN=KeyVaultTest"));
    Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals("CN=Root Agency"));

    // Retrieve the secret backing the certificate
    SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier();
    SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier());
    Assert.assertTrue(secret.managed());

    // Load the secret into a KeyStore
    String secretPassword = "";
    KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword);

    // Validate the certificate and key in the KeyStore
    validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword);

    CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(),
            certificateName);

    try {
        keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier());
    } catch (KeyVaultErrorException e) {
        Assert.assertNotNull(e.body().error());
        Assert.assertEquals("CertificateNotFound", e.body().error().code());
    }
}