Example usage for java.security.cert X509Certificate getSubjectDN

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

Introduction

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

Prototype

public abstract Principal getSubjectDN();

Source Link

Document

Denigrated, replaced by #getSubjectX500Principal() .

Usage

From source file:org.warlock.itk.distributionenvelope.Payload.java

/**
 * Add an X.509v3 certificate for a recipient.
 * /*w w  w.  j ava  2s .  c om*/
 * @param r 
 */
public void addReaderCertificate(X509Certificate r) throws Exception {
    if (r == null) {
        throw new Exception("Null certificate");
    }
    // Date range check against current date and time
    //
    r.checkValidity();

    // Allowed use check. Need to check that the certificate is issued
    // for usages that include "data encipherment". By default, require a
    // "key usage" extension unless the compile-time "allowNonUsageCertificates"
    // has been set.
    //
    // This is here where other certificate checking steps are handled elsewhere,
    // because the "data encipherment" usage is a specific usage type for the
    // content encryption.
    //
    boolean[] usage = r.getKeyUsage();
    if (usage != null) {
        if (!usage[DATAENCIPHERMENTUSAGE]) {
            throw new Exception(
                    "Certificate " + r.getSubjectDN().getName() + " not valid for data encipherment");
        }
    } else {
        if (!allowNonUsageCertificates) {
            throw new Exception("Certificate " + r.getSubjectDN().getName() + " has no key usage extension.");
        }
    }
    // This is included but commented out specifically to make the point that
    // section 4.2.1.3, "Key Usage" in RFC2459 says that the "key encipherment"
    // usage is for key management, so it isn't relevant here.
    //
    //        if (!usage[KEYENCIPHERMENTUSAGE]) {
    //            throw new Exception("Certificate " + r.getSubjectDN().getName() + " not valid for key encipherment");
    //        }
    encrypted = true;
    readerCerts.add(r);
}

From source file:org.warlock.itk.distributionenvelope.Payload.java

/**
 * Creates an XML Encryption "EncryptedKey" element using. Note that this does
 * NOT check the signing chain of the given certificate - the caller is responsible
 * for doing that since it makes assumptions about the availability of verification
 * and CRL information that the DistributionEnvelopeTools package cannot know about.
 * //from w w w .j a va  2  s . co  m
 * Note also that this made to encrypt 256 bit AES-256 keys. The Cipher.doFinal() call
 * used will handle this data size, but it has a maximum of 256 bytes - so if the code
 * is used for symmetric keys of 256 bytes or larger, it will need to be re-factored to
 * loop through the larger key.
 * 
 * @param cert X.509v3 certificate containing the reader's public key
 * @param k Symmetric key material
 * @return Serialised "EncryptedKey" element.
 * @throws Exception If something goes wrong.
 */
private String doRSASymmetricKeyEncryption(X509Certificate cert, byte[] k) throws Exception {
    // Encrypt the symmetric key using the given certificate...
    //
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, cert);
    byte[] c = cipher.doFinal(k);

    // ... then base64 encode the ciphertext and store it in an EncryptedKey
    // element, noting that the key is encrypted using RSA 1.5
    //
    Base64 b64 = new Base64();
    byte[] encryptedKey = b64.encode(c);
    StringBuilder sb = new StringBuilder(
            "<xenc:EncryptedKey><EncryptionMethod Algorithm=\"http://www.w3.org/2001/04/xmlenc#rsa-1_5\"/>");

    // Record the "reader" using the subject Distinguished Name of the given certificate,
    // and store it in the "KeyName" element. Receivers will use this to match "their" copy
    // of the encrypted symmetric key, with the private key they hold.
    //
    sb.append("<ds:KeyInfo><ds:KeyName>");
    sb.append(cert.getSubjectDN().getName());
    sb.append("</ds:KeyName></ds:KeyInfo>");
    sb.append("<xenc:CipherData><xenc:CipherValue>");
    sb.append(new String(encryptedKey));
    sb.append("</xenc:CipherValue></xenc:CipherData>");
    sb.append("</xenc:EncryptedKey>");
    return sb.toString();
}

From source file:it.cnr.icar.eric.client.ui.thin.RegistryBrowser.java

public void doClientCertAuthentication() {
    isSessionExpired = false;//from   w  w  w. j a  va2s.  c  om
    @SuppressWarnings("unused")
    String message = null;
    boolean noCredentialSet = false;
    try {
        String principalName = CommonProperties.getInstance()
                .getProperty("eric.security.anonymousUserPrincipalName");

        ConnectionImpl connection = getConnection();
        if (principalName != null) {
            // Set the CallbackHandler for JAAS authentication
            connection.setCallbackHandler(getCallbackHandler());

            // Get the credentials from the keystore and set them on the connection.
            // If no credentials were found, and the user is not a guest, 
            // generate the credentials.
            SecurityUtil.getInstance().handleCredentials(getPrincipal(), connection);
        } else {
            if (connection != null) {
                // Set the X509Certificate that will be presented to server side
                X509Certificate cert = getRequestCertificate();
                if (cert == null) {
                    reportAuthenticationFailure("cert");
                } else {
                    // Verify that the cert we obtained from JSSE has a valid user
                    // This is needed because some web browsers, such as Mozilla,
                    // cache the client certs and resubmit the cert on the 
                    // secure connection
                    UserType user = null;
                    try {
                        user = QueryManagerFactory.getInstance().getQueryManager().getUser(cert);
                    } catch (Throwable ex) {
                        log.error(WebUIResourceBundle.getInstance().getString("message.userNotFound",
                                new Object[] { cert.getSubjectDN().getName() }));
                    }
                    if (user == null) {
                        reportAuthenticationFailure("user");
                    } else {
                        connection.setX509Certificate(cert);
                        if (cert != null) {
                            HashSet<X509Certificate> credentials = new HashSet<X509Certificate>();
                            credentials.add(cert);
                            connection.setLocalCallMode(true);
                            connection.setCredentials(credentials);

                            this.principalName = getDisplayName();
                            //this.principalName = getDisplayName(user);
                        }
                        this.isCertLoaded = true;
                    }
                }
            }
        }
    } catch (Throwable t) {
        log.warn("Could not authenticate user with client cert", t);
        if (noCredentialSet) {
            this.errorMessage = WebUIResourceBundle.getInstance().getString("missingOrInvalidClientCert");
            helpLink = getUserRegistrationHelp();
        }
    }
}

From source file:com.netscape.cmscore.usrgrp.UGSubsystem.java

/**
 * Converts certificate into string format.
 * should eventually go into the locator itself
 *///from www .  j  a v  a2s  . c  o  m
protected String getCertificateStringWithoutVersion(X509Certificate cert) {
    if (cert == null) {
        return null;
    }
    // note that it did not represent a certificate fully
    return "-1;" + cert.getSerialNumber().toString() + ";" + cert.getIssuerDN() + ";" + cert.getSubjectDN();
}

From source file:com.netscape.cmscore.usrgrp.UGSubsystem.java

public String getCertificateString(X509Certificate cert) {
    if (cert == null) {
        return null;
    }/*from   ww  w . ja v a  2s  .  c o  m*/

    // note that it did not represent a certificate fully
    return cert.getVersion() + ";" + cert.getSerialNumber().toString() + ";" + cert.getIssuerDN() + ";"
            + cert.getSubjectDN();
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java

/**
 * adds a CA Using ECDSA keys to the database.
 *
 * It also checks that the CA is stored correctly.
 *
 * @throws Exception//from  w  w  w .ja va2s. c o m
 *           error
 */
private CAInfo addECDSACA(String dn, String keySpec) throws Exception {
    log.trace(">addECDSACA()");
    boolean ret = false;
    int cryptoTokenId = 0;
    CAInfo info = null;
    try {
        cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(admin, dn, keySpec);
        final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId,
                AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA, AlgorithmConstants.SIGALG_SHA1_WITH_RSA);
        // Create and active OSCP CA Service.
        List<ExtendedCAServiceInfo> extendedcaservices = new ArrayList<ExtendedCAServiceInfo>();
        extendedcaservices.add(new HardTokenEncryptCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE));
        extendedcaservices.add(new KeyRecoveryCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE));
        List<CertificatePolicy> policies = new ArrayList<CertificatePolicy>(1);
        policies.add(new CertificatePolicy("2.5.29.32.0", "", ""));

        X509CAInfo cainfo = new X509CAInfo(dn, dn, CAConstants.CA_ACTIVE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ROOTCA, 365, CAInfo.SELFSIGNED, null, catoken);
        cainfo.setDescription("JUnit ECDSA CA");
        cainfo.setPolicies(policies);
        cainfo.setExtendedCAServiceInfos(extendedcaservices);
        caAdminSession.createCA(admin, cainfo);

        info = caSession.getCAInfo(admin, dn);

        X509Certificate cert = (X509Certificate) info.getCertificateChain().iterator().next();
        assertTrue("Error in created ca certificate", cert.getSubjectDN().toString().equals(dn));
        assertTrue("Creating CA failed", info.getSubjectDN().equals(dn));
        // Make BC cert instead to make sure the public key is BC provider type (to make our test below easier)
        X509Certificate bccert = (X509Certificate) CertTools.getCertfromByteArray(cert.getEncoded());
        PublicKey pk = bccert.getPublicKey();
        if (pk instanceof JCEECPublicKey) {
            JCEECPublicKey ecpk = (JCEECPublicKey) pk;
            assertEquals(ecpk.getAlgorithm(), "EC");
            org.bouncycastle.jce.spec.ECParameterSpec spec = ecpk.getParameters();
            if (StringUtils.equals(keySpec, "implicitlyCA")) {
                assertNull("ImplicitlyCA must have null spec", spec);
            } else {
                assertNotNull("secp256r1 must not have null spec", spec);
            }
        } else if (pk instanceof BCECPublicKey) {
            BCECPublicKey ecpk = (BCECPublicKey) pk;
            assertEquals(ecpk.getAlgorithm(), "EC");
            org.bouncycastle.jce.spec.ECParameterSpec spec = ecpk.getParameters();
            if (StringUtils.equals(keySpec, "implicitlyCA")) {
                assertNull("ImplicitlyCA must have null spec", spec);
            } else {
                assertNotNull("secp256r1 must not have null spec", spec);
            }
        } else {
            assertTrue("Public key is not EC: " + pk.getClass().getName(), false);
        }

        ret = true;
    } catch (CAExistsException pee) {
        log.info("CA exists.");
    }
    assertTrue("Creating ECDSA CA failed", ret);
    log.trace("<addECDSACA()");
    return info;
}

From source file:be.fgov.kszbcss.rhq.websphere.connector.agent.ConnectorSubsystemComponent.java

public OperationResult invokeOperation(String name, Configuration parameters)
        throws InterruptedException, Exception {
    if (name.equals("importCertificateFromFile")) {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream in = new FileInputStream(parameters.getSimple("file").getStringValue());
        try {/*from   w ww. j a va  2s .  c om*/
            Iterator<? extends Certificate> it = cf.generateCertificates(in).iterator();
            if (it.hasNext()) {
                TrustStoreManager.getInstance().addCertificate(parameters.getSimple("alias").getStringValue(),
                        (X509Certificate) it.next());
            } else {
                throw new Exception("No certificate found");
            }
        } finally {
            in.close();
        }
        return null;
    } else if (name.equals("retrieveCellCertificate")) {
        DeploymentManager dm = new DeploymentManager(null, new ConfigurationBasedProcessLocator(parameters));
        String cell = dm.getCell();
        ConfigQueryExecutor configQueryExecutor = ConfigQueryServiceFactory.getInstance()
                .getConfigQueryExecutor(dm);
        try {
            X509Certificate cert = configQueryExecutor.query(CellRootCertificateQuery.INSTANCE);
            TrustStoreManager.getInstance().addCertificate("cell:" + cell, cert);
        } finally {
            configQueryExecutor.destroy();
        }
        return null;
    } else if (name.equals("retrieveCertificateFromPort")) {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(new KeyManager[0],
                new TrustManager[] {
                        new AutoImportTrustManager(parameters.getSimple("alias").getStringValue()) },
                new SecureRandom());
        SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket(
                parameters.getSimple("host").getStringValue(), parameters.getSimple("port").getIntegerValue());
        try {
            socket.startHandshake();
        } finally {
            socket.close();
        }
        return null;
    } else if (name.equals("listCertificates")) {
        final PropertyList certificates = new PropertyList("certificates");
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                // Sort the aliases for convenience
                Set<String> aliases = new TreeSet<String>();
                for (Enumeration<String> e = truststore.aliases(); e.hasMoreElements();) {
                    aliases.add(e.nextElement());
                }
                for (String alias : aliases) {
                    X509Certificate cert = (X509Certificate) truststore.getCertificate(alias);
                    PropertyMap map = new PropertyMap("certificate");
                    map.put(new PropertySimple("alias", alias));
                    map.put(new PropertySimple("subject", cert.getSubjectDN().toString()));
                    MessageDigest md = MessageDigest.getInstance("SHA-1");
                    md.update(cert.getEncoded());
                    byte[] digest = md.digest();
                    StringBuilder fingerprint = new StringBuilder();
                    for (int i = 0; i < digest.length; i++) {
                        if (i > 0) {
                            fingerprint.append(':');
                        }
                        fingerprint.append(getHexDigit(((int) digest[i] & 0xf0) >> 4));
                        fingerprint.append(getHexDigit((int) digest[i] & 0x0f));
                    }
                    map.put(new PropertySimple("fingerprint", fingerprint.toString()));
                    certificates.add(map);
                }
            }
        }, true);
        if (log.isDebugEnabled()) {
            log.debug("certificates=" + certificates);
        }
        OperationResult result = new OperationResult();
        result.getComplexResults().put(certificates);
        return result;
    } else if (name.equals("removeCertificate")) {
        final String alias = parameters.getSimple("alias").getStringValue();
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                truststore.deleteEntry(alias);
            }
        }, false);
        return null;
    } else if (name.equals("renameCertificate")) {
        final String oldAlias = parameters.getSimple("oldAlias").getStringValue();
        final String newAlias = parameters.getSimple("newAlias").getStringValue();
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                Certificate cert = truststore.getCertificate(oldAlias);
                truststore.setCertificateEntry(newAlias, cert);
                truststore.deleteEntry(oldAlias);
            }
        }, false);
        return null;
    } else {
        return null;
    }
}

From source file:org.ejbca.util.CertTools.java

/**
 * Gets subject or issuer DN in the format we are sure about (BouncyCastle),supporting UTF8.
 *
 * @param cert X509Certificate//from   w  w w . ja v  a  2 s  .com
 * @param which 1 = subjectDN, anything else = issuerDN
 *
 * @return String containing the DN.
 */
private static String getDN(Certificate cert, int which) {
    /*if (log.isTraceEnabled()) {
       log.trace(">getDN("+which+")");
    }*/
    String ret = null;
    if (cert == null) {
        return null;
    }
    if (cert instanceof X509Certificate) {
        // cert.getType=X.509
        try {
            CertificateFactory cf = CertTools.getCertificateFactory();
            X509Certificate x509cert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cert.getEncoded()));
            //log.debug("Created certificate of class: " + x509cert.getClass().getName());
            String dn = null;
            if (which == 1) {
                dn = x509cert.getSubjectDN().toString();
            } else {
                dn = x509cert.getIssuerDN().toString();
            }
            ret = stringToBCDNString(dn);
        } catch (CertificateException ce) {
            log.info("Could not get DN from X509Certificate. " + ce.getMessage());
            log.debug("", ce);
            return null;
        }
    } else if (StringUtils.equals(cert.getType(), "CVC")) {
        CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert;
        try {
            ReferenceField rf = null;
            if (which == 1) {
                rf = cvccert.getCVCertificate().getCertificateBody().getHolderReference();
            } else {
                rf = cvccert.getCVCertificate().getCertificateBody().getAuthorityReference();
            }
            if (rf != null) {
                // Construct a "fake" DN which can be used in EJBCA
                // Use only mnemonic and country, since sequence is more of a serialnumber than a DN part
                String dn = "";
                //                if (rf.getSequence() != null) {
                //                   dn += "SERIALNUMBER="+rf.getSequence();
                //                }
                if (rf.getMnemonic() != null) {
                    if (StringUtils.isNotEmpty(dn)) {
                        dn += ", ";
                    }
                    dn += "CN=" + rf.getMnemonic();
                }
                if (rf.getCountry() != null) {
                    if (StringUtils.isNotEmpty(dn)) {
                        dn += ", ";
                    }
                    dn += "C=" + rf.getCountry();
                }
                ret = stringToBCDNString(dn);
            }
        } catch (NoSuchFieldException e) {
            log.error("NoSuchFieldException: ", e);
            return null;
        }
    }
    /*if (log.isTraceEnabled()) {
       log.trace("<getDN("+which+"):"+dn);
    }*/
    return ret;
}