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:com.idevity.card.read.ShowCert.java

/**
 * Method onCreateView./*from w ww .  ja  v  a2  s  .c  o m*/
 * 
 * @param inflater
 *            LayoutInflater
 * @param container
 *            ViewGroup
 * @param savedInstanceState
 *            Bundle
 * @return View
 */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    Globals g = Globals.getInstance();

    byte[] _data = g.getCard();
    CardData80073 carddata = new CardData80073(_data);

    X509Certificate cardAuth = null;
    String issuer = new String();
    String subject = new String();
    String validfrom = new String();
    String validto = new String();
    try {
        PIVCertificate pca = null;
        PIVDataTempl dataTempl = carddata.getCardAuthCertificate();
        if (dataTempl != null) {
            byte[] data = dataTempl.getData();
            if (data == null) {
                data = dataTempl.getEncoded();
            }
            pca = new PIVCertificate(data);
        }
        cardAuth = pca.getCertificate();
    } catch (NullPointerException e) {
        if (debug) {
            Log.d(TAG, "Error: No Card Authentication Certificate Received");
        }
    } catch (Throwable e) {
        Log.e(TAG, "Error: " + e.getMessage());
    }
    if (cardAuth != null) {
        /*
         * The default implementation does not decode the
         * DN in a very human friendly form.  The following
         * Map and Format variables will help to better decode
         * the X500Principal object to a String value.
         */
        HashMap<String, String> oidMap = new HashMap<String, String>();
        oidMap.put("2.5.4.5", "SERIALNUMBER");
        String dnFormat = "RFC1779";
        /*
         * Get the values from the certificate
         */
        issuer = cardAuth.getIssuerX500Principal().getName(dnFormat, oidMap);
        subject = cardAuth.getSubjectX500Principal().getName(dnFormat, oidMap);
        validfrom = cardAuth.getNotBefore().toString();
        validto = cardAuth.getNotAfter().toString();
        /*
         * Populate the UI
         */
        View certLayout = inflater.inflate(R.layout.activity_show_cert, container, false);
        ImageView valPeriodIndicator = (ImageView) certLayout.findViewById(R.id.cert_ind_vp);
        ImageView popIndicator = (ImageView) certLayout.findViewById(R.id.cert_ind_pop);
        TextView valPeriodLabel = (TextView) certLayout.findViewById(R.id.cert_vp_label);
        TextView popLabel = (TextView) certLayout.findViewById(R.id.cert_pop_label);
        TextView vfText = (TextView) certLayout.findViewById(R.id.cert_nb_label);
        TextView vtText = (TextView) certLayout.findViewById(R.id.cert_na_label);
        /*
         * Assume the cert is good unless an exception
         * is thrown below.
         */
        valPeriodIndicator.setImageResource(R.drawable.cert_good);

        /*
         * Note to self.  I am not thrilled how Java almost forces you
         * to assume a certificate if valid unless an exception is thrown!
         */
        try {
            cardAuth.checkValidity();
        } catch (CertificateNotYetValidException e) {
            valPeriodIndicator.setImageResource(R.drawable.cert_bad);
            valPeriodLabel.setTextColor(getResources().getColor(R.color.idredmain));
            vfText.setTextColor(getResources().getColor(R.color.idredmain));
            if (debug) {
                Log.d(TAG, "Error: Authentication Certificate Not Valid Yet!");
            }
        } catch (CertificateExpiredException e) {
            valPeriodIndicator.setImageResource(R.drawable.cert_bad);
            valPeriodLabel.setTextColor(getResources().getColor(R.color.idredmain));
            vtText.setTextColor(getResources().getColor(R.color.idredmain));
            if (debug) {
                Log.d(TAG, "Error: Card Authentication Certificate Expired!");
            }
        }
        CAKChallenge popVerify = new CAKChallenge(cardAuth, carddata.getCAKPoPNonce(), carddata.getCAKPoPSig());
        try {
            if (popVerify.validatePOP()) {
                popIndicator.setImageResource(R.drawable.cert_good);
                if (debug) {
                    Log.d(TAG, "Proof of Possession Verified!");
                }
            } else {
                popIndicator.setImageResource(R.drawable.cert_bad);
                popLabel.setTextColor(getResources().getColor(R.color.idredmain));
                if (debug) {
                    Log.d(TAG, "Proof of Possession Failed!");
                }
            }
        } catch (SignatureException e) {
            popIndicator.setImageResource(R.drawable.cert_bad);
            popLabel.setTextColor(getResources().getColor(R.color.idredmain));
            if (debug) {
                Log.d(TAG, "Problem with Proof of Possession: " + e.getMessage());
            }
        }
        TextView editCertSubject = (TextView) certLayout.findViewById(R.id.cert_sub_dn);
        editCertSubject.setText(subject);

        TextView editValidFrom = (TextView) certLayout.findViewById(R.id.cert_nb_date);
        editValidFrom.setText(validfrom);

        TextView editValidTo = (TextView) certLayout.findViewById(R.id.cert_na_date);
        editValidTo.setText(validto);

        TextView editIssuer = (TextView) certLayout.findViewById(R.id.cert_iss_dn);
        editIssuer.setText(issuer);
        return certLayout;
    } else {
        View certLayout = inflater.inflate(R.layout.activity_no_cert, container, false);
        return certLayout;
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.MockX509SecurityHandler.java

@Override
public X509SecurityManagerMaterial generateMaterial(X509MaterialParameter materialParameter) throws Exception {
    ApplicationId appId = materialParameter.getApplicationId();
    String appUser = materialParameter.getAppUser();
    Integer cryptoMaterialVersion = materialParameter.getCryptoMaterialVersion();

    KeyPair keyPair = generateKeyPair();
    PKCS10CertificationRequest csr = generateCSR(appId, appUser, keyPair, cryptoMaterialVersion);
    assertEquals(appUser, HopsUtil.extractCNFromSubject(csr.getSubject().toString()));
    assertEquals(appId.toString(), HopsUtil.extractOFromSubject(csr.getSubject().toString()));
    assertEquals(String.valueOf(cryptoMaterialVersion),
            HopsUtil.extractOUFromSubject(csr.getSubject().toString()));

    // Sign CSR/*from   w ww.ja  va 2 s.  c o m*/
    CertificateBundle certificateBundle = sendCSRAndGetSigned(csr);
    certificateBundle.getCertificate().checkValidity();
    long expiration = certificateBundle.getCertificate().getNotAfter().getTime();
    long epochNow = DateUtils.localDateTime2UnixEpoch(DateUtils.getNow());
    assertTrue(expiration >= epochNow);
    assertNotNull(certificateBundle.getIssuer());
    RMAppSecurityActions actor = getRmAppSecurityActions();
    if (actor instanceof TestingRMAppSecurityActions) {
        X509Certificate caCert = ((TestingRMAppSecurityActions) actor).getCaCert();
        certificateBundle.getCertificate().verify(caCert.getPublicKey(), "BC");
    }
    certificateBundle.getCertificate().verify(certificateBundle.getIssuer().getPublicKey(), "BC");

    KeyStoresWrapper appKeystores = createApplicationStores(certificateBundle, keyPair.getPrivate(), appUser,
            appId);
    X509Certificate extractedCert = (X509Certificate) appKeystores.getKeystore().getCertificate(appUser);
    byte[] rawKeystore = appKeystores.getRawKeyStore(TYPE.KEYSTORE);
    assertNotNull(rawKeystore);
    assertNotEquals(0, rawKeystore.length);

    File keystoreFile = Paths.get(systemTMP, appUser + "-" + appId.toString() + "_kstore.jks").toFile();
    // Keystore should have been deleted
    assertFalse(keystoreFile.exists());
    char[] keyStorePassword = appKeystores.getKeyStorePassword();
    assertNotNull(keyStorePassword);
    assertNotEquals(0, keyStorePassword.length);

    byte[] rawTrustStore = appKeystores.getRawKeyStore(TYPE.TRUSTSTORE);
    File trustStoreFile = Paths.get(systemTMP, appUser + "-" + appId.toString() + "_tstore.jks").toFile();
    // Truststore should have been deleted
    assertFalse(trustStoreFile.exists());
    char[] trustStorePassword = appKeystores.getTrustStorePassword();
    assertNotNull(trustStorePassword);
    assertNotEquals(0, trustStorePassword.length);

    verifyContentOfAppTrustStore(rawTrustStore, trustStorePassword, appUser, appId);

    if (actor instanceof TestingRMAppSecurityActions) {
        X509Certificate caCert = ((TestingRMAppSecurityActions) actor).getCaCert();
        extractedCert.verify(caCert.getPublicKey(), "BC");
    }
    assertEquals(appUser, HopsUtil.extractCNFromSubject(extractedCert.getSubjectX500Principal().getName()));
    assertEquals(appId.toString(),
            HopsUtil.extractOFromSubject(extractedCert.getSubjectX500Principal().getName()));
    assertEquals(String.valueOf(cryptoMaterialVersion),
            HopsUtil.extractOUFromSubject(extractedCert.getSubjectX500Principal().getName()));
    return new X509SecurityManagerMaterial(appId, rawKeystore, appKeystores.getKeyStorePassword(),
            rawTrustStore, appKeystores.getTrustStorePassword(), expiration);
}

From source file:jproxy.ProxyControl.java

public String[] getCertificateDetails() {
    if (isDynamicMode()) {
        try {/*  w  ww  .j a va2s.  c  o m*/
            X509Certificate caCert = (X509Certificate) keyStore.getCertificate(KeyToolUtils.getRootCAalias());
            if (caCert == null) {
                return new String[] { "Could not find certificate" };
            }
            return new String[] { caCert.getSubjectX500Principal().toString(),
                    "Fingerprint(SHA1): "
                            + JOrphanUtils.baToHexString(DigestUtils.sha1(caCert.getEncoded()), ' '),
                    "Created: " + caCert.getNotBefore().toString() };
        } catch (GeneralSecurityException e) {
            log.error("Problem reading root CA from keystore", e);
            return new String[] { "Problem with root certificate", e.getMessage() };
        }
    }
    return null; // should not happen
}

From source file:be.fedict.eid.tsl.Tsl2PdfExporter.java

/**
 * Produce a human readable export of the given tsl to the given file.
 * /*from   w w w. j  a  v a  2s . c  o  m*/
 * @param tsl
 *            the TrustServiceList to export
 * @param pdfFile
 *            the file to generate
 * @return
 * @throws IOException
 */
public void humanReadableExport(final TrustServiceList tsl, final File pdfFile) {
    Document document = new Document();
    OutputStream outputStream;
    try {
        outputStream = new FileOutputStream(pdfFile);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("file not found: " + pdfFile.getAbsolutePath(), e);
    }
    try {
        final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);
        pdfWriter.setPDFXConformance(PdfWriter.PDFA1B);

        // title
        final EUCountry country = EUCountry.valueOf(tsl.getSchemeTerritory());
        final String title = country.getShortSrcLangName() + " (" + country.getShortEnglishName()
                + "): Trusted List";

        Phrase footerPhrase = new Phrase("PDF document generated on " + new Date().toString() + ", page ",
                headerFooterFont);
        HeaderFooter footer = new HeaderFooter(footerPhrase, true);
        document.setFooter(footer);

        Phrase headerPhrase = new Phrase(title, headerFooterFont);
        HeaderFooter header = new HeaderFooter(headerPhrase, false);
        document.setHeader(header);

        document.open();
        addTitle(title, title0Font, Paragraph.ALIGN_CENTER, 0, 20, document);

        addLongItem("Scheme name", tsl.getSchemeName(), document);
        addLongItem("Legal Notice", tsl.getLegalNotice(), document);

        // information table
        PdfPTable informationTable = createInfoTable();
        addItemRow("Scheme territory", tsl.getSchemeTerritory(), informationTable);
        addItemRow("Scheme status determination approach",
                substringAfter(tsl.getStatusDeterminationApproach(), "StatusDetn/"), informationTable);
        /*
        final List<String> schemeTypes = new ArrayList<String>();
        for (final String schemeType : tsl.getSchemeTypes()) {
           schemeTypes.add(schemeType);
        }
        */
        final List<String> schemeTypes = new ArrayList<String>();
        List<NonEmptyMultiLangURIType> uris = tsl.getSchemeTypes();
        for (NonEmptyMultiLangURIType uri : uris) {
            schemeTypes.add(uri.getValue());
        }
        addItemRow("Scheme type community rules", schemeTypes, informationTable);

        addItemRow("Issue date", tsl.getListIssueDateTime().toString(), informationTable);
        addItemRow("Next update", tsl.getNextUpdate().toString(), informationTable);
        addItemRow("Historical information period", tsl.getHistoricalInformationPeriod().toString() + " days",
                informationTable);
        addItemRow("Sequence number", tsl.getSequenceNumber().toString(), informationTable);
        addItemRow("Scheme information URIs", tsl.getSchemeInformationUris(), informationTable);

        document.add(informationTable);

        addTitle("Scheme Operator", title1Font, Paragraph.ALIGN_CENTER, 0, 10, document);

        informationTable = createInfoTable();
        addItemRow("Scheme operator name", tsl.getSchemeOperatorName(), informationTable);
        PostalAddressType schemeOperatorPostalAddress = tsl.getSchemeOperatorPostalAddress(Locale.ENGLISH);
        addItemRow("Scheme operator street address", schemeOperatorPostalAddress.getStreetAddress(),
                informationTable);
        addItemRow("Scheme operator postal code", schemeOperatorPostalAddress.getPostalCode(),
                informationTable);
        addItemRow("Scheme operator locality", schemeOperatorPostalAddress.getLocality(), informationTable);
        addItemRow("Scheme operator state", schemeOperatorPostalAddress.getStateOrProvince(), informationTable);
        addItemRow("Scheme operator country", schemeOperatorPostalAddress.getCountryName(), informationTable);

        List<String> schemeOperatorElectronicAddressess = tsl.getSchemeOperatorElectronicAddresses();
        addItemRow("Scheme operator contact", schemeOperatorElectronicAddressess, informationTable);
        document.add(informationTable);

        addTitle("Trust Service Providers", title1Font, Paragraph.ALIGN_CENTER, 10, 2, document);

        List<TrustServiceProvider> trustServiceProviders = tsl.getTrustServiceProviders();
        for (TrustServiceProvider trustServiceProvider : trustServiceProviders) {
            addTitle(trustServiceProvider.getName(), title1Font, Paragraph.ALIGN_LEFT, 10, 2, document);

            PdfPTable providerTable = createInfoTable();
            addItemRow("Service provider trade name", trustServiceProvider.getTradeNames(), providerTable);
            addItemRow("Information URI", trustServiceProvider.getInformationUris(), providerTable);
            PostalAddressType postalAddress = trustServiceProvider.getPostalAddress();
            addItemRow("Service provider street address", postalAddress.getStreetAddress(), providerTable);
            addItemRow("Service provider postal code", postalAddress.getPostalCode(), providerTable);
            addItemRow("Service provider locality", postalAddress.getLocality(), providerTable);
            addItemRow("Service provider state", postalAddress.getStateOrProvince(), providerTable);
            addItemRow("Service provider country", postalAddress.getCountryName(), providerTable);
            document.add(providerTable);

            List<TrustService> trustServices = trustServiceProvider.getTrustServices();
            for (TrustService trustService : trustServices) {
                addTitle(trustService.getName(), title2Font, Paragraph.ALIGN_LEFT, 10, 2, document);
                PdfPTable serviceTable = createInfoTable();
                addItemRow("Type", substringAfter(trustService.getType(), "Svctype/"), serviceTable);
                addItemRow("Status", substringAfter(trustService.getStatus(), "Svcstatus/"), serviceTable);
                addItemRow("Status starting time", trustService.getStatusStartingTime().toString(),
                        serviceTable);
                document.add(serviceTable);

                addTitle("Service digital identity (X509)", title3Font, Paragraph.ALIGN_LEFT, 2, 0, document);
                final X509Certificate certificate = trustService.getServiceDigitalIdentity();
                final PdfPTable serviceIdentityTable = createInfoTable();
                addItemRow("Version", Integer.toString(certificate.getVersion()), serviceIdentityTable);
                addItemRow("Serial number", certificate.getSerialNumber().toString(), serviceIdentityTable);
                addItemRow("Signature algorithm", certificate.getSigAlgName(), serviceIdentityTable);
                addItemRow("Issuer", certificate.getIssuerX500Principal().toString(), serviceIdentityTable);
                addItemRow("Valid from", certificate.getNotBefore().toString(), serviceIdentityTable);
                addItemRow("Valid to", certificate.getNotAfter().toString(), serviceIdentityTable);
                addItemRow("Subject", certificate.getSubjectX500Principal().toString(), serviceIdentityTable);
                addItemRow("Public key", certificate.getPublicKey().toString(), serviceIdentityTable);
                // TODO certificate policies
                addItemRow("Subject key identifier", toHex(getSKId(certificate)), serviceIdentityTable);
                addItemRow("CRL distribution points", getCrlDistributionPoints(certificate),
                        serviceIdentityTable);
                addItemRow("Authority key identifier", toHex(getAKId(certificate)), serviceIdentityTable);
                addItemRow("Key usage", getKeyUsage(certificate), serviceIdentityTable);
                addItemRow("Basic constraints", getBasicConstraints(certificate), serviceIdentityTable);

                byte[] encodedCertificate;
                try {
                    encodedCertificate = certificate.getEncoded();
                } catch (CertificateEncodingException e) {
                    throw new RuntimeException("cert: " + e.getMessage(), e);
                }
                addItemRow("SHA1 Thumbprint", DigestUtils.shaHex(encodedCertificate), serviceIdentityTable);
                addItemRow("SHA256 Thumbprint", DigestUtils.sha256Hex(encodedCertificate),
                        serviceIdentityTable);
                document.add(serviceIdentityTable);

                //add Scheme service definition 
                if (null != trustService.getSchemeServiceDefinitionURI()) {
                    addTitle("Scheme Service Definition URI", title3Font, Paragraph.ALIGN_LEFT, 2, 0, document);
                    final PdfPTable schemeServiceDefinitionURITabel = createInfoTable();
                    for (NonEmptyMultiLangURIType uri : trustService.getSchemeServiceDefinitionURI().getURI()) {
                        addItemRow(uri.getLang(), uri.getValue(), schemeServiceDefinitionURITabel);
                    }
                    document.add(schemeServiceDefinitionURITabel);
                }

                List<ExtensionType> extensions = trustService.getExtensions();
                for (ExtensionType extension : extensions) {
                    printExtension(extension, document);
                }

                addLongMonoItem("The decoded certificate:", certificate.toString(), document);
                addLongMonoItem("The certificate in PEM format:", toPem(certificate), document);

                ServiceHistoryType serviceHistoryType = trustService.getServiceHistoryInstanceType();

                if (null != serviceHistoryType) {

                    for (ServiceHistoryInstanceType serviceHistoryInstanceType : serviceHistoryType
                            .getServiceHistoryInstance()) {
                        PdfPTable serviceHistoryTable = createInfoTable();

                        //Service approval history information
                        addTitle("Service approval history information", title3Font, Paragraph.ALIGN_LEFT, 10,
                                2, document);

                        // service type identifier
                        //5.6.2 Service name
                        InternationalNamesType i18nServiceName = serviceHistoryInstanceType.getServiceName();
                        String servName = TrustServiceListUtils.getValue(i18nServiceName, Locale.ENGLISH);
                        addItemRow("Name", servName, serviceHistoryTable);
                        //5.6.1 Service type identifier
                        addItemRow("Type", substringAfter(serviceHistoryInstanceType.getServiceTypeIdentifier(),
                                "Svctype/"), serviceHistoryTable);
                        addItemRow("Status", serviceHistoryInstanceType.getServiceStatus(),
                                serviceHistoryTable);
                        //5.6.4 Service previous status
                        addItemRow("Previous status", serviceHistoryInstanceType.getServiceStatus(),
                                serviceHistoryTable);
                        //5.6.5 Previous status starting date and time
                        addItemRow(
                                "Previous starting time", new DateTime(serviceHistoryInstanceType
                                        .getStatusStartingTime().toGregorianCalendar()).toString(),
                                serviceHistoryTable);
                        //5.6.3 Service digital identity
                        final X509Certificate previousCertificate = trustService.getServiceDigitalIdentity(
                                serviceHistoryInstanceType.getServiceDigitalIdentity());

                        document.add(serviceHistoryTable);

                        addTitle("Service digital identity (X509)", title4Font, Paragraph.ALIGN_LEFT, 2, 0,
                                document);

                        final PdfPTable serviceIdentityTableHistory = createInfoTable();
                        addItemRow("Version", Integer.toString(previousCertificate.getVersion()),
                                serviceIdentityTableHistory);
                        addItemRow("Serial number", previousCertificate.getSerialNumber().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Signature algorithm", previousCertificate.getSigAlgName(),
                                serviceIdentityTableHistory);
                        addItemRow("Issuer", previousCertificate.getIssuerX500Principal().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Valid from", previousCertificate.getNotBefore().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Valid to", previousCertificate.getNotAfter().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Subject", previousCertificate.getSubjectX500Principal().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Public key", previousCertificate.getPublicKey().toString(),
                                serviceIdentityTableHistory);
                        // TODO certificate policies
                        addItemRow("Subject key identifier", toHex(getSKId(previousCertificate)),
                                serviceIdentityTableHistory);
                        addItemRow("CRL distribution points", getCrlDistributionPoints(previousCertificate),
                                serviceIdentityTableHistory);
                        addItemRow("Authority key identifier", toHex(getAKId(previousCertificate)),
                                serviceIdentityTableHistory);
                        addItemRow("Key usage", getKeyUsage(previousCertificate), serviceIdentityTableHistory);
                        addItemRow("Basic constraints", getBasicConstraints(previousCertificate),
                                serviceIdentityTableHistory);

                        byte[] encodedHistoryCertificate;
                        try {
                            encodedHistoryCertificate = previousCertificate.getEncoded();
                        } catch (CertificateEncodingException e) {
                            throw new RuntimeException("cert: " + e.getMessage(), e);
                        }
                        addItemRow("SHA1 Thumbprint", DigestUtils.shaHex(encodedHistoryCertificate),
                                serviceIdentityTableHistory);
                        addItemRow("SHA256 Thumbprint", DigestUtils.sha256Hex(encodedHistoryCertificate),
                                serviceIdentityTableHistory);
                        document.add(serviceIdentityTableHistory);

                        ExtensionsListType previousExtensions = serviceHistoryInstanceType
                                .getServiceInformationExtensions();
                        if (null != previousExtensions) {
                            for (ExtensionType extension : previousExtensions.getExtension()) {
                                printExtension(extension, document);
                            }
                        }

                        addLongMonoItem("The decoded certificate:", previousCertificate.toString(), document);
                        addLongMonoItem("The certificate in PEM format:", toPem(previousCertificate), document);
                    }
                }
            }
        }

        X509Certificate signerCertificate = tsl.verifySignature();
        if (null != signerCertificate) {
            Paragraph tslSignerTitle = new Paragraph("Trusted List Signer", title1Font);
            tslSignerTitle.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(tslSignerTitle);

            final PdfPTable signerTable = createInfoTable();
            addItemRow("Subject", signerCertificate.getSubjectX500Principal().toString(), signerTable);
            addItemRow("Issuer", signerCertificate.getIssuerX500Principal().toString(), signerTable);
            addItemRow("Not before", signerCertificate.getNotBefore().toString(), signerTable);
            addItemRow("Not after", signerCertificate.getNotAfter().toString(), signerTable);
            addItemRow("Serial number", signerCertificate.getSerialNumber().toString(), signerTable);
            addItemRow("Version", Integer.toString(signerCertificate.getVersion()), signerTable);
            byte[] encodedPublicKey = signerCertificate.getPublicKey().getEncoded();
            addItemRow("Public key SHA1 Thumbprint", DigestUtils.shaHex(encodedPublicKey), signerTable);
            addItemRow("Public key SHA256 Thumbprint", DigestUtils.sha256Hex(encodedPublicKey), signerTable);
            document.add(signerTable);

            addLongMonoItem("The decoded certificate:", signerCertificate.toString(), document);
            addLongMonoItem("The certificate in PEM format:", toPem(signerCertificate), document);
            addLongMonoItem("The public key in PEM format:", toPem(signerCertificate.getPublicKey()), document);
        }

        document.close();
    } catch (DocumentException e) {
        throw new RuntimeException("PDF document error: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new RuntimeException("Exception: " + e.getMessage(), e);
    }
}

From source file:org.kse.gui.actions.SignCsrAction.java

/**
 * Do action./*from w ww. j av a  2 s. c o  m*/
 */
@Override
protected void doAction() {
    FileOutputStream fos = null;
    File caReplyFile = null;

    try {
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStoreState currentState = history.getCurrentState();

        String alias = kseFrame.getSelectedEntryAlias();

        Password password = getEntryPassword(alias, currentState);

        if (password == null) {
            return;
        }

        KeyStore keyStore = currentState.getKeyStore();

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
        Certificate[] certs = keyStore.getCertificateChain(alias);

        KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey);

        File csrFile = chooseCsrFile();
        if (csrFile == null) {
            return;
        }

        PKCS10CertificationRequest pkcs10Csr = null;
        Spkac spkacCsr = null;

        try {
            CryptoFileType fileType = CryptoFileUtil.detectFileType(new FileInputStream(csrFile));
            if (fileType == CryptoFileType.PKCS10_CSR) {
                pkcs10Csr = Pkcs10Util.loadCsr(new FileInputStream(csrFile));

                if (!Pkcs10Util.verifyCsr(pkcs10Csr)) {
                    JOptionPane.showMessageDialog(frame,
                            res.getString("SignCsrAction.NoVerifyPkcs10Csr.message"),
                            res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
                    return;
                }
            } else if (fileType == CryptoFileType.SPKAC_CSR) {
                spkacCsr = new Spkac(new FileInputStream(csrFile));

                if (!spkacCsr.verify()) {
                    JOptionPane.showMessageDialog(frame,
                            res.getString("SignCsrAction.NoVerifySpkacCsr.message"),
                            res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
                    return;
                }
            } else {
                JOptionPane.showMessageDialog(frame,
                        MessageFormat.format(res.getString("SignCsrAction.FileNotRecognisedType.message"),
                                csrFile),
                        res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
                return;
            }
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(frame,
                    MessageFormat.format(res.getString("SignCsrAction.NotFile.message"), csrFile),
                    res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
            return;
        } catch (Exception ex) {
            String problemStr = MessageFormat.format(res.getString("SignCsrAction.NoOpenCsr.Problem"),
                    csrFile.getName());

            String[] causes = new String[] { res.getString("SignCsrAction.NotCsr.Cause"),
                    res.getString("SignCsrAction.CorruptedCsr.Cause") };

            Problem problem = new Problem(problemStr, causes, ex);

            DProblem dProblem = new DProblem(frame, res.getString("SignCsrAction.ProblemOpeningCsr.Title"),
                    problem);
            dProblem.setLocationRelativeTo(frame);
            dProblem.setVisible(true);

            return;
        }

        X509Certificate[] signingChain = X509CertUtil
                .orderX509CertChain(X509CertUtil.convertCertificates(certs));
        X509Certificate signingCert = signingChain[0];

        PublicKey publicKey = null;
        X500Name subject = null;
        DSignCsr dSignCsr = null;
        Provider provider = history.getExplicitProvider();

        if (pkcs10Csr != null) {
            publicKey = new JcaPKCS10CertificationRequest(pkcs10Csr).getPublicKey();
            subject = pkcs10Csr.getSubject();

            dSignCsr = new DSignCsr(frame, pkcs10Csr, csrFile, privateKey, keyPairType, signingCert, provider);
        } else {
            publicKey = spkacCsr.getPublicKey();
            subject = spkacCsr.getSubject().getName();

            dSignCsr = new DSignCsr(frame, spkacCsr, csrFile, privateKey, keyPairType, signingCert, provider);
        }

        dSignCsr.setLocationRelativeTo(frame);
        dSignCsr.setVisible(true);

        X509CertificateVersion version = dSignCsr.getVersion();
        SignatureType signatureType = dSignCsr.getSignatureType();
        Date validityStart = dSignCsr.getValidityStart();
        Date validityEnd = dSignCsr.getValidityEnd();
        BigInteger serialNumber = dSignCsr.getSerialNumber();
        caReplyFile = dSignCsr.getCaReplyFile();
        X509ExtensionSet extensions = dSignCsr.getExtensions();

        if (version == null) {
            return;
        }

        X500Name issuer = X500NameUtils.x500PrincipalToX500Name(signingCert.getSubjectX500Principal());

        // CA Reply is a cert with subject from CSR and issuer from signing cert's subject
        X509CertificateGenerator generator = new X509CertificateGenerator(version);
        X509Certificate caReplyCert = generator.generate(subject, issuer, validityStart, validityEnd, publicKey,
                privateKey, signatureType, serialNumber, extensions, provider);

        X509Certificate[] caReplyChain = new X509Certificate[signingChain.length + 1];

        caReplyChain[0] = caReplyCert;

        // Add all of the signing chain to the reply
        System.arraycopy(signingChain, 0, caReplyChain, 1, signingChain.length);

        byte[] caCertEncoded = X509CertUtil.getCertsEncodedPkcs7(caReplyChain);

        fos = new FileOutputStream(caReplyFile);
        fos.write(caCertEncoded);
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(frame,
                MessageFormat.format(res.getString("SignJarAction.NoWriteFile.message"), caReplyFile),
                res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE);
        return;
    } catch (Exception ex) {
        DError.displayError(frame, ex);
        return;
    } finally {
        IOUtils.closeQuietly(fos);
    }

    JOptionPane.showMessageDialog(frame, res.getString("SignCsrAction.SignCsrSuccessful.message"),
            res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.INFORMATION_MESSAGE);
}

From source file:org.glite.security.voms.admin.persistence.dao.VOMSUserDAO.java

public Certificate addCertificate(VOMSUser u, X509Certificate x509Cert) {

    Validate.notNull(u, "User must be non-null!");
    Validate.notNull(x509Cert, "Certificate must be non-null!");

    // Assume the certificate have been already validated
    // at this stage.

    String caDN = DNUtil.getOpenSSLSubject(x509Cert.getIssuerX500Principal());
    VOMSCA ca = VOMSCADAO.instance().getByName(caDN);

    if (ca == null)
        throw new NoSuchCAException("CA '" + caDN + "' not recognized!");

    Certificate cert = CertificateDAO.instance().find(x509Cert);

    if (cert != null)
        throw new AlreadyExistsException("Certificate already bound!");

    cert = new Certificate();

    String subjectString = DNUtil.getOpenSSLSubject(x509Cert.getSubjectX500Principal());
    cert.setSubjectString(subjectString);
    cert.setCreationTime(new Date());
    cert.setSuspended(false);//w ww  . ja va  2s  .c  om
    cert.setCa(ca);

    cert.setUser(u);

    if (u.isSuspended()) {
        cert.setSuspended(true);
        cert.setSuspensionReason(u.getSuspensionReason());
    }

    u.addCertificate(cert);

    HibernateFactory.getSession().saveOrUpdate(cert);
    HibernateFactory.getSession().saveOrUpdate(u);

    return cert;

}

From source file:org.ejbca.core.protocol.ws.EjbcaWSTest.java

@Test
public void test19RevocationApprovals() throws Exception {
    log.trace(">test19RevocationApprovals");
    final String APPROVINGADMINNAME = "superadmin";
    final String TOKENSERIALNUMBER = "42424242";
    final String TOKENUSERNAME = "WSTESTTOKENUSER3";
    final String ERRORNOTSENTFORAPPROVAL = "The request was never sent for approval.";
    final String ERRORNOTSUPPORTEDSUCCEEDED = "Reactivation of users is not supported, but succeeded anyway.";

    // Generate random username and CA name
    String randomPostfix = Integer.toString(secureRandom.nextInt(999999));
    String caname = "wsRevocationCA" + randomPostfix;
    String username = "wsRevocationUser" + randomPostfix;
    int cryptoTokenId = 0;
    int caID = -1;
    try {//  w  w  w.  j  a  v a 2s. co m
        cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(intAdmin, caname, "1024");
        final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId,
                AlgorithmConstants.SIGALG_SHA1_WITH_RSA, AlgorithmConstants.SIGALG_SHA1_WITH_RSA);
        caID = RevocationApprovalTest.createApprovalCA(intAdmin, caname, CAInfo.REQ_APPROVAL_REVOCATION,
                caAdminSessionRemote, caSession, catoken);
        X509Certificate adminCert = (X509Certificate) certificateStoreSession
                .findCertificatesByUsername(APPROVINGADMINNAME).iterator().next();
        Set<X509Certificate> credentials = new HashSet<X509Certificate>();
        credentials.add(adminCert);
        Set<Principal> principals = new HashSet<Principal>();
        principals.add(adminCert.getSubjectX500Principal());
        AuthenticationToken approvingAdmin = simpleAuthenticationProvider
                .authenticate(new AuthenticationSubject(principals, credentials));
        //AuthenticationToken approvingAdmin = new X509CertificateAuthenticationToken(principals, credentials);
        //Admin approvingAdmin = new Admin(adminCert, APPROVINGADMINNAME, null);
        try {
            X509Certificate cert = createUserAndCert(username, caID);
            String issuerdn = cert.getIssuerDN().toString();
            String serno = cert.getSerialNumber().toString(16);
            // revoke via WS and verify response
            try {
                ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (WaitingForApprovalException_Exception e1) {
            }
            try {
                ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (ApprovalException_Exception e1) {
            }
            RevokeStatus revokestatus = ejbcaraws.checkRevokationStatus(issuerdn, serno);
            assertNotNull(revokestatus);
            assertTrue(revokestatus.getReason() == RevokedCertInfo.NOT_REVOKED);
            // Approve revocation and verify success
            approveRevocation(intAdmin, approvingAdmin, username,
                    RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD,
                    ApprovalDataVO.APPROVALTYPE_REVOKECERTIFICATE, certificateStoreSession, approvalSession,
                    approvalExecutionSession, caID);
            // Try to unrevoke certificate
            try {
                ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.NOT_REVOKED);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (WaitingForApprovalException_Exception e) {
            }
            try {
                ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.NOT_REVOKED);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (ApprovalException_Exception e) {
            }
            // Approve revocation and verify success
            approveRevocation(intAdmin, approvingAdmin, username, RevokedCertInfo.NOT_REVOKED,
                    ApprovalDataVO.APPROVALTYPE_REVOKECERTIFICATE, certificateStoreSession, approvalSession,
                    approvalExecutionSession, caID);
            // Revoke user
            try {
                ejbcaraws.revokeUser(username, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, false);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (WaitingForApprovalException_Exception e) {
            }
            try {
                ejbcaraws.revokeUser(username, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, false);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (ApprovalException_Exception e) {
            }
            // Approve revocation and verify success
            approveRevocation(intAdmin, approvingAdmin, username,
                    RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD,
                    ApprovalDataVO.APPROVALTYPE_REVOKEENDENTITY, certificateStoreSession, approvalSession,
                    approvalExecutionSession, caID);
            // Try to reactivate user
            try {
                ejbcaraws.revokeUser(username, RevokedCertInfo.NOT_REVOKED, false);
                assertTrue(ERRORNOTSUPPORTEDSUCCEEDED, false);
            } catch (AlreadyRevokedException_Exception e) {
            }
        } finally {
            endEntityManagementSession.deleteUser(intAdmin, username);
        }
        try {
            // Create a hard token issued by this CA
            createHardToken(TOKENUSERNAME, caname, TOKENSERIALNUMBER);
            assertTrue(ejbcaraws.existsHardToken(TOKENSERIALNUMBER));
            // Revoke token
            try {
                ejbcaraws.revokeToken(TOKENSERIALNUMBER, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (WaitingForApprovalException_Exception e) {
            }
            try {
                ejbcaraws.revokeToken(TOKENSERIALNUMBER, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (ApprovalException_Exception e) {
            }
            // Approve actions and verify success
            approveRevocation(intAdmin, approvingAdmin, TOKENUSERNAME,
                    RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD,
                    ApprovalDataVO.APPROVALTYPE_REVOKECERTIFICATE, certificateStoreSession, approvalSession,
                    approvalExecutionSession, caID);
        } finally {
            hardTokenSessionRemote.removeHardToken(intAdmin, TOKENSERIALNUMBER);
        }
    } finally {
        // Nuke CA
        try {
            caAdminSessionRemote.revokeCA(intAdmin, caID, RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED);
        } finally {
            caSession.removeCA(intAdmin, caID);
            CryptoTokenTestUtils.removeCryptoToken(intAdmin, cryptoTokenId);
        }
    }
    log.trace("<test19RevocationApprovals");
}

From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java

/**
 * Sends a KeyUpdateRequest by an admin concerning a certificate of another EndEntity in client mode. 
 * If the CA enforces unique public key, a CMP error message is expected and no certificate renewal.
 * If the CA does not enforce unique public key, a certificate will be renewed, though not the expected EndEntity certificate, but the admin certificate is renewed.
 * //from   w  w  w  .j  a  v  a  2  s .c  om
 * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal)
 * - Pre-configuration: Sets the cmp.authenticationmodule to 'EndEntityCertificate'
 * - Pre-configuration: Sets the cmp.authenticationparameters to 'TestCA'
 * - Pre-configuration: Sets the cmp.allowautomatickeyupdate to 'true'
 * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful.
 * - Generates a CMP KeyUpdate Request and tests that such request has been created.
 * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null
 * - Verifies the signature of the CMP request
 * - Sends the request using HTTP and receives an response.
 * - Examines the response:
 *      - Checks that the response is not empty or null
 *      - Checks that the protection algorithm is sha1WithRSAEncryption
 *      - Check that the signer is the expected CA
 *      - Verifies the response signature
 *      - Checks that the response's senderNonce is 16 bytes long
 *      - Checks that the request's senderNonce is the same as the response's recipientNonce
 *      - Checks that the request and the response has the same transactionID
 *      - Obtains the certificate from the response
 *      - Checks that the obtained certificate has the right subjectDN and issuerDN
 * 
 * @throws Exception
 */
@Test
public void test13AdminInClientMode() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace("test09RAMode()");
    }

    this.cmpConfiguration.setRAMode(this.cmpAlias, false);
    this.cmpConfiguration.setAuthenticationModule(this.cmpAlias,
            CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "TestCA");
    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //------------------ create the user and issue his first certificate -------------
    createUser(this.username, this.userDN.toString(), "foo123");
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final Certificate certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123",
            new PublicKeyWrapper(keys.getPublic()));
    assertNotNull("Failed to create a test certificate", certificate);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, this.userDN,
            this.issuerDN, pAlg, new DEROctetString("CMPTESTPROFILE".getBytes()));
    assertNotNull("Failed to generate a CMP renewal request", req);
    //int reqId = req.getBody().getKur().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue();

    createUser("cmpTestAdmin", "CN=cmpTestAdmin,C=SE", "foo123");
    KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
    AuthenticationToken admToken = createAdminToken(admkeys, "cmpTestAdmin", "CN=cmpTestAdmin,C=SE");
    Certificate admCert = getCertFromCredentials(admToken);
    CMPCertificate[] extraCert = getCMPCert(admCert);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    //send request and recieve response
    byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    CAInfo cainfo = this.caSession.getCAInfo(ADMIN, this.caid);
    if (cainfo.isDoEnforceUniquePublicKeys()) {
        final PKIBody body = respObject.getBody();
        assertEquals(23, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        final String expectedErrMsg = "User 'cmpTestAdmin' is not allowed to use same key as another user is using.";
        assertEquals(expectedErrMsg, errMsg);
    } else {
        PKIBody body = respObject.getBody();
        int tag = body.getType();
        assertEquals(8, tag);
        CertRepMessage c = (CertRepMessage) body.getContent();
        assertNotNull(c);
        CMPCertificate cmpcert = c.getResponse()[0].getCertifiedKeyPair().getCertOrEncCert().getCertificate();
        assertNotNull(cmpcert);
        X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(cmpcert.getEncoded());
        assertNotNull("Failed to renew the certificate", cert);
        assertEquals("CN=cmpTestAdmin, C=SE", cert.getSubjectX500Principal().toString());
    }

    removeAuthenticationToken(admToken, admCert, "cmpTestAdmin");

    if (log.isTraceEnabled()) {
        log.trace("<test09RAMode()");
    }
}

From source file:org.texai.x509.X509Utils.java

/** Generates a signed end-use certificate that cannot be used to sign other certificates, but can be used for authentication
 * and for message signing./*  w w  w. j av a  2 s  . c  o  m*/
 *
 * @param myPublicKey the public key for this certificate
 * @param issuerPrivateKey the issuer's private key
 * @param issuerCertificate the issuer's certificate
 * @param uid the subject UID
 * @param domainComponent the domain component, e.g. TexaiLauncher or NodeRuntime
 * @return a signed end-use certificate
 *
 * @throws CertificateParsingException when the certificate cannot be parsed
 * @throws CertificateEncodingException when the certificate cannot be encoded
 * @throws NoSuchProviderException when an invalid provider is given
 * @throws NoSuchAlgorithmException when an invalid algorithm is given
 * @throws SignatureException when the an invalid signature is present
 * @throws InvalidKeyException when the given key is invalid
 * @throws IOException if an input/output error occurs while processing the serial number file
 */
public static X509Certificate generateX509Certificate(final PublicKey myPublicKey,
        final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, final UUID uid,
        final String domainComponent)
        throws CertificateParsingException, CertificateEncodingException, NoSuchProviderException,
        NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException {
    //Preconditions
    assert myPublicKey != null : "myPublicKey must not be null";
    assert issuerPrivateKey != null : "issuerPrivateKey must not be null";
    assert issuerCertificate != null : "issuerCertificate must not be null";
    assert uid != null : "uid must not be null";

    final String x500PrincipalString;
    // provide items to X500Principal in reverse order
    if (domainComponent == null || domainComponent.isEmpty()) {
        x500PrincipalString = "UID=" + uid + ", CN=texai.org";
    } else {
        x500PrincipalString = "UID=" + uid + ", DC=" + domainComponent + " ,CN=texai.org";
    }
    final X500Principal x500Principal = new X500Principal(x500PrincipalString);

    LOGGER.info("issuer: " + issuerCertificate.getIssuerX500Principal().getName());

    final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(
            new X500Name(StringUtils
                    .reverseCommaDelimitedString(issuerCertificate.getSubjectX500Principal().getName())), // issuer,
            getNextSerialNumber(), // serial
            new Date(System.currentTimeMillis() - 10000L), // notBefore,
            new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter,
            new X500Name(x500Principal.getName()), // subject,
            new SubjectPublicKeyInfo(ASN1Sequence.getInstance(myPublicKey.getEncoded()))); // publicKeyInfo

    // see http://www.ietf.org/rfc/rfc3280.txt
    // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication
    final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
    // Add authority key identifier
    x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCertificate));

    // Add subject key identifier
    x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createSubjectKeyIdentifier(myPublicKey));

    // add basic constraints
    x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical
            new BasicConstraints(false)); // is not a CA certificate

    // add key usage
    final KeyUsage keyUsage = new KeyUsage(
            // the digitalSignature usage indicates that the subject public key may be used with a digital signature
            // mechanism to support security services other than non-repudiation, certificate signing, or revocation
            // information signing
            KeyUsage.digitalSignature | // the nonRepudiation usage indicates that the subject public key may be used to verify digital signatures
                                        // used to provide a non-repudiation service which protects against the signing entity falsely denying some
                                        // action, excluding certificate or CRL signing
                    KeyUsage.nonRepudiation | // the keyEncipherment usage indicates that the subject public key may be used for key transport, e.g. the
                                              // exchange of efficient symmetric keys in SSL
                    KeyUsage.keyEncipherment | // the dataEncipherment usage indicates that the subject public key may be used for enciphering user data,
                                               // other than cryptographic keys
                    KeyUsage.dataEncipherment | // the keyAgreement usage indicates that the subject public key may be used for key agreement, e.g. when a
                                                // Diffie-Hellman key is to be used for key management
                    KeyUsage.keyAgreement | // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on
                                            // certificates
                    KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation
                                           // information
                    KeyUsage.cRLSign | // see http://www.docjar.com/html/api/sun/security/validator/EndEntityChecker.java.html - bit 0 needs to set for SSL
                                       // client authorization
                    KeyUsage.encipherOnly);
    x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical
            keyUsage);

    X509Certificate x509Certificate;
    try {
        final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM)
                .setProvider(BOUNCY_CASTLE_PROVIDER).build(issuerPrivateKey);
        final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);
        final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
        x509Certificate = makeCanonicalX509Certificate(
                jcaX509CertificateConverter.getCertificate(x509CertificateHolder));
    } catch (CertificateException | OperatorCreationException ex) {
        throw new TexaiException(ex);
    }

    //Postconditions
    try {
        x509Certificate.checkValidity();
        x509Certificate.verify(issuerCertificate.getPublicKey());
    } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException
            | SignatureException ex) {
        throw new TexaiException(ex);
    }
    assert x509Certificate.getKeyUsage()[0] : "must have digital signature key usage";

    return x509Certificate;
}

From source file:eu.europa.ec.markt.tlmanager.core.validation.Validation.java

/**
 * Validates a ServiceDigitalIdentities by comparing its values with its certificate (if any). 
 * Furthermore, there has to be a certificate for a service and either a certificate, ski or subject name
 * for a history.//w ww .  j  a  v a 2  s .  co m
 * 
 * @param name the name of the governing object node
 * @param type the type to check
 * @param parent the reference object
 * @param certNotMandatory if true, it is not mandatory to have a certificate, but at least a subject name or ski
 */
private void validateSpecial(NODENAMES name, DigitalIdentityListType type, Object parent,
        boolean certNotMandatory) {
    boolean gotCert = false, gotSubName = false, gotSKI = false;
    String field = QNames._ServiceDigitalIdentities_QNAME.getLocalPart();
    if (type == null) {
        logger.error(logger.getEmptyMessage(name.toString(), field), parent);
        return;
    }

    X500Principal certSName = null, sName = null;
    byte[] certSki = null, ski = null;
    List<DigitalIdentityType> digitalIds = type.getDigitalId();
    // first check on all the data that is available
    for (DigitalIdentityType ids : digitalIds) {
        if (ids.getX509Certificate() != null) {
            try {
                ByteArrayInputStream bais = new ByteArrayInputStream(ids.getX509Certificate());
                X509Certificate certificate = DSSUtils.loadCertificate(bais);
                gotCert = true;

                certSName = certificate.getSubjectX500Principal();
                certSki = DSSUtils.getSki(certificate);
            } catch (DSSException ce) {
                String message = uiKeys
                        .getString("Validation.mandatory.certificate.invalid" + " - " + ce.getMessage());
                LOG.log(Level.SEVERE, message);
                logger.error(message, parent);
            }
        } else if (ids.getX509SubjectName() != null) {
            gotSubName = true;
            sName = new X500Principal(ids.getX509SubjectName());
        } else if (ids.getX509SKI() != null) {
            gotSKI = true;
            ski = ids.getX509SKI();
        }
    }

    // check 'internal' inconsistencies
    if (sName != null && certSName != null && !sName.equals(certSName)) {
        logger.error(uiKeys.getString("Validation.mandatory.certificate.mismatch.subjectname"), parent);
    }

    if (ski != null && certSki != null) {
        byte[] shorterSki = ski;
        byte[] longerSki = certSki;
        if (ski.length != certSki.length) {
            if (ski.length > certSki.length) {
                shorterSki = certSki;
                longerSki = ski;
            }
            longerSki = Arrays.copyOfRange(longerSki, longerSki.length - shorterSki.length, longerSki.length);
        }
        if (!Arrays.equals(shorterSki, longerSki)) {
            logger.error(uiKeys.getString("Validation.mandatory.certificate.mismatch.ski"), parent);
        }
    }

    if (certNotMandatory) { // history
        if (!gotSubName && !gotSKI && !gotCert) {
            logger.error(logger.getEmptyMessage(name.toString(), field), parent);
        } else if (!gotSubName) { // subjectname is recommended
            logger.warn(logger.getPrefix(name.toString(), field)
                    + uiKeys.getString("Validation.mandatory.certificate.noSubjectName"), parent);
        }
    } else { // service
        if (!gotCert) {
            logger.error(logger.getEmptyMessage(name.toString(), field), parent);
        }
    }
}