Example usage for java.security.cert X509Certificate getSerialNumber

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

Introduction

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

Prototype

public abstract BigInteger getSerialNumber();

Source Link

Document

Gets the serialNumber value from the certificate.

Usage

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

public void test04RevocationApprovals() throws Exception {
    // Generate random username and CA name
    String randomPostfix = Integer.toString((new Random(new Date().getTime() + 4711)).nextInt(999999));
    String caname = "cmpRevocationCA" + randomPostfix;
    String username = "cmpRevocationUser" + randomPostfix;
    X509CAInfo cainfo = null;// w  w w.j  a v  a 2 s.c o m
    try {
        // Generate CA with approvals for revocation enabled
        int caID = RevocationApprovalTest.createApprovalCA(admin, caname, CAInfo.REQ_APPROVAL_REVOCATION,
                caAdminSession, caSession);
        // Get CA cert
        cainfo = (X509CAInfo) caAdminSession.getCAInfo(admin, caID);
        assertNotNull(cainfo);
        X509Certificate newCACert = (X509Certificate) cainfo.getCertificateChain().iterator().next();
        // Create a user and generate the cert
        UserDataVO userdata = new UserDataVO(username, "CN=" + username, cainfo.getCAId(), null, null, 1,
                SecConst.EMPTY_ENDENTITYPROFILE, SecConst.CERTPROFILE_FIXED_ENDUSER, SecConst.TOKEN_SOFT_P12, 0,
                null);
        userdata.setPassword("foo123");
        userAdminSession.addUser(admin, userdata, true);
        BatchMakeP12 makep12 = new BatchMakeP12();
        File tmpfile = File.createTempFile("ejbca", "p12");
        makep12.setMainStoreDir(tmpfile.getParent());
        makep12.createAllNew();
        Collection<java.security.cert.Certificate> userCerts = certificateStoreSession
                .findCertificatesByUsername(admin, username);
        assertTrue(userCerts.size() == 1);
        X509Certificate cert = (X509Certificate) userCerts.iterator().next();
        // revoke via CMP and verify response
        byte[] nonce = CmpMessageHelper.createSenderNonce();
        byte[] transid = CmpMessageHelper.createSenderNonce();
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        PKIMessage rev = genRevReq(cainfo.getSubjectDN(), userdata.getDN(), cert.getSerialNumber(), newCACert,
                nonce, transid, true);
        PKIMessage revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
        assertNotNull(revReq);
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        out.writeObject(revReq);
        byte[] ba = bao.toByteArray();
        byte[] resp = sendCmpHttp(ba, 200);
        checkCmpResponseGeneral(resp, cainfo.getSubjectDN(), userdata.getDN(), newCACert, nonce, transid, false,
                PBEPASSWORD);
        checkCmpRevokeConfirmMessage(cainfo.getSubjectDN(), userdata.getDN(), cert.getSerialNumber(), newCACert,
                resp, true);
        int reason = checkRevokeStatus(cainfo.getSubjectDN(), cert.getSerialNumber());
        assertEquals(reason, RevokedCertInfo.NOT_REVOKED);
        // try to revoke one more via CMP and verify error
        nonce = CmpMessageHelper.createSenderNonce();
        transid = CmpMessageHelper.createSenderNonce();
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        rev = genRevReq(cainfo.getSubjectDN(), userdata.getDN(), cert.getSerialNumber(), newCACert, nonce,
                transid, true);
        revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
        assertNotNull(revReq);
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        out.writeObject(revReq);
        ba = bao.toByteArray();
        resp = sendCmpHttp(ba, 200);
        checkCmpResponseGeneral(resp, cainfo.getSubjectDN(), userdata.getDN(), newCACert, nonce, transid, false,
                PBEPASSWORD);
        checkCmpFailMessage(resp, "The request is already awaiting approval.",
                CmpPKIBodyConstants.REVOCATIONRESPONSE, 0, ResponseStatus.FAILURE.getIntValue());
        reason = checkRevokeStatus(cainfo.getSubjectDN(), cert.getSerialNumber());
        assertEquals(reason, RevokedCertInfo.NOT_REVOKED);
        // Approve revocation and verify success
        Admin approvingAdmin = new Admin((X509Certificate) certificateStoreSession
                .findCertificatesByUsername(admin, APPROVINGADMINNAME).iterator().next(), APPROVINGADMINNAME,
                null);
        approveRevocation(admin, approvingAdmin, username,
                RevokedCertInfo.REVOCATION_REASON_CESSATIONOFOPERATION,
                ApprovalDataVO.APPROVALTYPE_REVOKECERTIFICATE, certificateStoreSession, approvalSession,
                approvalExecutionSession, cainfo.getCAId());
        // try to revoke the now revoked cert via CMP and verify error
        nonce = CmpMessageHelper.createSenderNonce();
        transid = CmpMessageHelper.createSenderNonce();
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        rev = genRevReq(cainfo.getSubjectDN(), userdata.getDN(), cert.getSerialNumber(), newCACert, nonce,
                transid, true);
        revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
        assertNotNull(revReq);
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        out.writeObject(revReq);
        ba = bao.toByteArray();
        resp = sendCmpHttp(ba, 200);
        checkCmpResponseGeneral(resp, cainfo.getSubjectDN(), userdata.getDN(), newCACert, nonce, transid, false,
                PBEPASSWORD);
        checkCmpFailMessage(resp, "Already revoked.", CmpPKIBodyConstants.REVOCATIONRESPONSE, 0,
                ResponseStatus.FAILURE.getIntValue());
    } finally {
        // Delete user
        userAdminSession.deleteUser(admin, username);
        // Nuke CA
        try {
            caAdminSession.revokeCA(admin, cainfo.getCAId(), RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED);
        } finally {
            caSession.removeCA(admin, cainfo.getCAId());
        }
    }
}

From source file:com.mhise.util.MHISEUtil.java

public static boolean saveImportedCertificateToDevice(String certificate, String password, Context ctx,
        String certName) {// w  w  w  .ja  va 2  s  .c o  m
    boolean isPasswordCorrect = false;

    byte[] certificatebytes = null;

    try {
        certificatebytes = Base64.decode(certificate, Base64.DEFAULT);
    } catch (IllegalArgumentException e) {
        // TODO: handle exception
        Logger.debug("MHISEUtil-->saveImportedCertificateToDevice", "" + e);
    }
    KeyStore localTrustStore = null;
    try {
        localTrustStore = KeyStore.getInstance("PKCS12");
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    InputStream is = new ByteArrayInputStream(certificatebytes);
    try {
        localTrustStore.load(is, password.toCharArray());
        isPasswordCorrect = true;

    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }

    OutputStream fos = null;
    try {
        //<<<<<<< .mine
        //SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME,Context.MODE_PRIVATE);
        //String  storeName =sharedPreferences.getString(Constants.KEY_CERT_NAME, null);

        File _mobiusDirectory = new File(Constants.defaultP12StorePath);

        if (!_mobiusDirectory.exists()) {
            _mobiusDirectory.mkdir();
        }

        File file = new File(Constants.defaultP12StorePath + certName);
        fos = new FileOutputStream(file);
        //fos = ctx.openFileOutput(Constants.defaultP12StoreName, Context.MODE_PRIVATE);
        localTrustStore.store(fos, MHISEUtil.getStrongPassword(certName).toCharArray());
        /*//=======
                    //SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME,Context.MODE_PRIVATE);
                    //String  storeName =sharedPreferences.getString(Constants.KEY_CERT_NAME, null);
                            
                            
                    File file = new File(Constants.defaultP12StorePath+certName);
                     fos = new FileOutputStream(file);
                    //fos = ctx.openFileOutput(Constants.defaultP12StoreName, Context.MODE_PRIVATE);
                    localTrustStore.store(fos,MHISEUtil.getStrongPassword(certName).toCharArray());
        >>>>>>> .r4477*/
        fos.close();

        Enumeration<String> aliases = null;
        try {
            aliases = localTrustStore.aliases();
        } catch (KeyStoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //boolean isInstalledCertificateValid = false;

        while (aliases.hasMoreElements()) {

            String alias = aliases.nextElement();
            java.security.cert.X509Certificate cert = null;
            try {
                cert = (X509Certificate) localTrustStore.getCertificate(alias);
            } catch (KeyStoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            SharedPreferences sharedPreferences1 = ctx.getSharedPreferences(Constants.PREFS_NAME,
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences1.edit();

            Log.i("Imported certificate serial number", "" + cert.getSerialNumber().toString(16));
            editor.putString(Constants.KEY_SERIAL_NUMBER, "" + cert.getSerialNumber().toString(16));
            editor.commit();

        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return isPasswordCorrect;
}

From source file:eu.europa.ec.markt.dss.report.Tsl2PdfExporter.java

/**
 * Produce a human readable export of the given tsl to the given file.
 * /*from ww w  . jav a2s  .co  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);
        }
        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.getTradeName(), 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);

                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);
            }
        }

        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:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java

/**
 * Test conversion to byte array and back.
 *//*from w w  w .  j  a  va2 s .  c  o m*/
@Test
public void testTestRoundtrip() throws GeneralSecurityException {
    populate(builder);
    X509Certificate expected = builder.build(keyPair.getPrivate());

    X509Certificate actual = certUtil.getCertificate(expected.getEncoded());
    assertEquals(actual.getSerialNumber(), expected.getSerialNumber());
    assertEquals(actual.getIssuerDN().toString(), expected.getIssuerDN().toString());
    assertEquals(actual.getSubjectDN().toString(), expected.getSubjectDN().toString());
    assertEquals(actual.getNotBefore(), expected.getNotBefore());
    assertEquals(actual.getNotAfter(), expected.getNotAfter());
}

From source file:org.apache.directory.studio.connection.ui.widgets.CertificateInfoComposite.java

/**
 * Sets the input for this composite. //  ww  w. j  a  v a2  s .  co  m
 *
 * @param certificateChain certificate chain input
 */
public void setInput(X509Certificate[] certificateChain) {
    X509Certificate certificate = certificateChain[0];

    X500Principal issuedToPrincipal = certificate.getSubjectX500Principal();
    Map<String, String> issuedToAttributes = getAttributeMap(issuedToPrincipal);
    issuedToCN.setText(issuedToAttributes.get("CN")); //$NON-NLS-1$
    issuedToO.setText(issuedToAttributes.get("O")); //$NON-NLS-1$
    issuedToOU.setText(issuedToAttributes.get("OU")); //$NON-NLS-1$
    serialNumber.setText(certificate.getSerialNumber().toString(16));

    X500Principal issuedFromPrincipal = certificate.getIssuerX500Principal();
    Map<String, String> issuedFromAttributes = getAttributeMap(issuedFromPrincipal);
    issuedByCN.setText(issuedFromAttributes.get("CN")); //$NON-NLS-1$
    issuedByO.setText(issuedFromAttributes.get("O")); //$NON-NLS-1$
    issuedByOU.setText(issuedFromAttributes.get("OU")); //$NON-NLS-1$

    issuesOn.setText(DateFormatUtils.ISO_DATE_FORMAT.format(certificate.getNotBefore()));
    expiresOn.setText(DateFormatUtils.ISO_DATE_FORMAT.format(certificate.getNotAfter()));

    byte[] encoded2 = null;

    try {
        encoded2 = certificate.getEncoded();
    } catch (CertificateEncodingException e) {
    }

    byte[] md5 = DigestUtils.md5(encoded2);
    String md5HexString = getHexString(md5);
    fingerprintMD5.setText(md5HexString);
    byte[] sha = DigestUtils.sha(encoded2);
    String shaHexString = getHexString(sha);
    fingerprintSHA1.setText(shaHexString);

    // Details: certificate chain
    CertificateChainItem parentItem = null;
    CertificateChainItem certificateItem = null;

    for (X509Certificate cert : certificateChain) {
        CertificateChainItem item = new CertificateChainItem(cert);

        if (parentItem != null) {
            item.child = parentItem;
            parentItem.parent = item;
        }

        if (certificateItem == null) {
            certificateItem = item;
        }

        parentItem = item;
    }

    hierarchyTreeViewer.setInput(new CertificateChainItem[] { parentItem });
    hierarchyTreeViewer.expandAll();
    hierarchyTreeViewer.setSelection(new StructuredSelection(certificateItem), true);

    // Details: 
    certificateTree.removeAll();
    populateCertificateTree();
    valueText.setText(StringUtils.EMPTY);
}

From source file:com.qut.middleware.esoemanager.manager.logic.impl.ServiceCryptoImpl.java

public void createServiceKey(String serviceID) throws ServiceCryptoCreationException {
    String keyStorePassphrase;/*from  ww  w  .  ja  v a2  s . c  o  m*/
    String keyPairName;
    String keyPairPassphrase;
    String keyPairSubjectDN;
    KeyPair spKeyPair;
    KeyStore keyStore;
    byte[] keyStoreBytes;

    try {
        Integer entID = new Integer(serviceID);

        if (entID.intValue() == this.esoeENTID) {
            keyPairSubjectDN = this.generateSubjectDN(this.esoeEntityID);
        } else {
            String serviceURL = null;
            Map<String, Object> description = this.managerDAO.queryServiceDescription(entID);
            if (description == null)
                throw new ServiceCryptoCreationException("Unable to retrieve serviceURL for this service");

            serviceURL = (String) description.get(Constants.FIELD_SERVICE_URL);
            keyPairSubjectDN = this.generateSubjectDN(serviceURL);
        }

        keyPairName = this.identifierGenerator.generateXMLKeyName();

        keyStorePassphrase = this.generatePassphrase();
        keyPairPassphrase = this.generatePassphrase();

        keyStore = this.cryptoProcessor.generateKeyStore();
        spKeyPair = this.cryptoProcessor.generateKeyPair();
        this.cryptoProcessor.addKeyPair(keyStore, keyStorePassphrase, spKeyPair, keyPairName, keyPairPassphrase,
                keyPairSubjectDN);
        keyStoreBytes = this.cryptoProcessor.convertKeystoreByteArray(keyStore, keyStorePassphrase);

        X509Certificate certificate = (X509Certificate) keyStore.getCertificate(keyPairName);

        /* Determine expiry date of PKI data */
        Calendar expiryDate = Calendar.getInstance();
        expiryDate.add(Calendar.YEAR, this.cryptoProcessor.getCertExpiryIntervalInYears());

        if (entID.intValue() == this.esoeENTID) {
            /** Commit key data to IDP reference */
            Integer descID_IDP = this.managerDAO.getDescID(entID, Constants.IDP_DESCRIPTOR);
            this.managerDAO.insertPublicKey(descID_IDP, expiryDate.getTime(), keyPairName,
                    this.cryptoProcessor.getCertIssuerDN(), certificate.getSerialNumber().toString(),
                    this.cryptoProcessor.convertPublicKeyByteArray(spKeyPair.getPublic()));

            this.managerDAO.insertPKIData(descID_IDP, expiryDate.getTime(), keyStoreBytes, keyStorePassphrase,
                    keyPairName, keyPairPassphrase);

            /** Commit key data to PDP reference */
            Integer descID_PDP = this.managerDAO.getDescID(entID, Constants.LXACML_PDP_DESCRIPTOR);
            this.managerDAO.insertPublicKey(descID_PDP, expiryDate.getTime(), keyPairName,
                    this.cryptoProcessor.getCertIssuerDN(), certificate.getSerialNumber().toString(),
                    this.cryptoProcessor.convertPublicKeyByteArray(spKeyPair.getPublic()));

            this.managerDAO.insertPKIData(descID_PDP, expiryDate.getTime(), keyStoreBytes, keyStorePassphrase,
                    keyPairName, keyPairPassphrase);

            /** Commit key data to Attribute Authority reference */
            Integer descID_AA = this.managerDAO.getDescID(entID, Constants.ATTRIBUTE_AUTHORITY_DESCRIPTOR);
            this.managerDAO.insertPublicKey(descID_AA, expiryDate.getTime(), keyPairName,
                    this.cryptoProcessor.getCertIssuerDN(), certificate.getSerialNumber().toString(),
                    this.cryptoProcessor.convertPublicKeyByteArray(spKeyPair.getPublic()));

            this.managerDAO.insertPKIData(descID_AA, expiryDate.getTime(), keyStoreBytes, keyStorePassphrase,
                    keyPairName, keyPairPassphrase);
        } else {
            Integer descID = this.managerDAO.getDescID(entID, Constants.SP_DESCRIPTOR);
            this.managerDAO.insertPublicKey(descID, expiryDate.getTime(), keyPairName,
                    this.cryptoProcessor.getCertIssuerDN(), certificate.getSerialNumber().toString(),
                    this.cryptoProcessor.convertPublicKeyByteArray(spKeyPair.getPublic()));
            this.managerDAO.insertPKIData(descID, expiryDate.getTime(), keyStoreBytes, keyStorePassphrase,
                    keyPairName, keyPairPassphrase);
        }

    } catch (NumberFormatException e) {
        throw new ServiceCryptoCreationException(e.getLocalizedMessage(), e);
    } catch (ManagerDAOException e) {
        throw new ServiceCryptoCreationException(e.getLocalizedMessage(), e);
    } catch (CryptoException e) {
        throw new ServiceCryptoCreationException(e.getLocalizedMessage(), e);
    } catch (KeyStoreException e) {
        throw new ServiceCryptoCreationException("Could not obtain certificate from new keystore.", e);
    }
}

From source file:edu.washington.shibboleth.attribute.resolver.provider.dataConnector.RwsDataConnector.java

/**
 * This sets the trust managers that will be used for all TLS and SSL connections to the ldap. This method will
 * remove any cached results and initialize the connection manager.
 * //from   w ww .j  av  a  2 s  .  c o  m
 * @see #clearCache()
 * @see #setSslSocketFactory(SSLSocketFactory)
 * 
 * @param tc <code>X509Credential</code> to create TrustManagers with
 */
public void setSslTrustManagers(X509Credential tc) {
    if (tc != null) {
        try {
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            for (X509Certificate c : tc.getEntityCertificateChain()) {
                keystore.setCertificateEntry("ldap_tls_trust_" + c.getSerialNumber(), c);
            }
            tmf.init(keystore);
            sslTrustManagers = tmf.getTrustManagers();
        } catch (GeneralSecurityException e) {
            log.error("Error initializing trust managers", e);
        } catch (IOException e) {
            log.error("Error initializing trust managers", e);
        }
    }
}

From source file:ch.bfh.unicert.certimport.Certificate.java

/**
 * Create an object representing a X509 certificate with redundant information
 * @param cert the X509 certificate to store in the object
 * @param commonName the common name appearing in the given certificate
 * @param uniqueId the unique identifier appearing in the given certificate
 * @param organisation the organisation appearing in the given certificate
 * @param organisationUnit the organisation unit appearing in the given certificate
 * @param countryName the country appearing in the given certificate
 * @param state the state appearing in the given certificate
 * @param locality the locality appearing in the given certificate
 * @param surname the surname appearing in the given certificate
 * @param givenName the given name appearing in the given certificate
 * @param applicationIdentifier the identifier of the application the certificate is issued for
 * @param role the role the certificate is issued certificate
 * @param identityProvider the identity provider used to authenticate the requester of the certificate
 * @param extension the extension appearing in the given certificate
 * /*  w  ww  . ja v  a2 s .c  om*/
 * If some information does not appear in the certificate, null can be passed
 */
public Certificate(X509Certificate cert, String commonName, String uniqueId, String organisation,
        String organisationUnit, String countryName, String state, String locality, String surname,
        String givenName, String applicationIdentifier, String[] roles, String identityProvider,
        Map extension) {

    this.commonName = commonName;
    this.uniqueIdentifier = uniqueId;
    this.organisation = organisation;
    this.organisationUnit = organisationUnit;
    this.countryName = countryName;
    this.state = state;
    this.locality = locality;
    this.surname = surname;
    this.givenName = givenName;

    this.issuer = cert.getIssuerDN().getName();
    this.serialNumber = cert.getSerialNumber();
    this.validFrom = cert.getNotBefore();
    this.validUntil = cert.getNotAfter();
    this.applicationIdentifier = applicationIdentifier;
    this.roles = roles;
    this.identityProvider = identityProvider;
    this.extension = extension;
    try {
        this.pem = CertificateHelper.x509ToBase64PEMString(cert);
    } catch (IOException ex) {

        Logger.getLogger(Certificate.class.getName()).log(Level.SEVERE, null, ex);
    }
    this.cert = cert;
}

From source file:org.signserver.admin.gui.ViewCertificateFrame.java

private void viewCertificate(final X509Certificate certificate) {
    this.certificate = certificate;
    if (certificate == null) {
        fields = null;//from   w  w w. java  2 s  . c  o m

    } else {
        fields = new ArrayList<Field>();

        fields.add(new Field("Version", String.valueOf(certificate.getVersion())));
        fields.add(new Field("Serial Number", certificate.getSerialNumber().toString(16)));
        fields.add(new Field("Certificate Signature Algorithm", String.valueOf(certificate.getSigAlgName())));
        fields.add(new Field("Issuer", String.valueOf(certificate.getIssuerDN())));
        fields.add(new Field("Validity Not Before", String.valueOf(certificate.getNotBefore())));
        fields.add(new Field("Validity Not After", String.valueOf(certificate.getNotAfter())));
        fields.add(new Field("Subject", String.valueOf(certificate.getSubjectDN())));
        fields.add(new Field("Subject Public Key Algorithm",
                String.valueOf(certificate.getPublicKey().getAlgorithm())));
        fields.add(new Field("Subject's Public Key",
                new String(Hex.encode(certificate.getPublicKey().getEncoded()))));
        if (certificate.getCriticalExtensionOIDs() != null) {
            for (String extensionOid : certificate.getCriticalExtensionOIDs()) {
                fields.add(new Field("Critical extension: " + extensionOid, "<Not supported yet>"));
            }
        }
        if (certificate.getNonCriticalExtensionOIDs() != null) {
            for (String extensionOid : certificate.getNonCriticalExtensionOIDs()) {
                fields.add(new Field("Non critical extension: " + extensionOid, "<Not supported yet>"));
            }
        }
        fields.add(new Field("Certificate Signature Algorithm", String.valueOf(certificate.getSigAlgName())));
        fields.add(
                new Field("Certificate Signature Value", new String(Hex.encode(certificate.getSignature()))));

        fieldsList.setModel(new AbstractListModel() {

            @Override
            public int getSize() {
                return fields.size();
            }

            @Override
            public Object getElementAt(int index) {
                return fields.get(index);
            }
        });
    }
}

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

/**
 * Gets the OCSP status for the specified subject and issuer certificates.
 *
 * @param ocspStatusKey status key//from w w  w.  ja  v a 2  s. c  om
 * @return ocsp status
 */
private OcspStatus getOcspStatus(final OcspRequest ocspStatusKey) {
    final X509Certificate subjectCertificate = ocspStatusKey.getSubjectCertificate();
    final X509Certificate issuerCertificate = ocspStatusKey.getIssuerCertificate();

    // initialize the default status
    final OcspStatus ocspStatus = new OcspStatus();
    ocspStatus.setVerificationStatus(VerificationStatus.Unknown);
    ocspStatus.setValidationStatus(ValidationStatus.Unknown);

    try {
        // prepare the request
        final BigInteger subjectSerialNumber = subjectCertificate.getSerialNumber();
        final DigestCalculatorProvider calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                .setProvider("BC").build();
        final CertificateID certificateId = new CertificateID(
                calculatorProviderBuilder.get(CertificateID.HASH_SHA1),
                new X509CertificateHolder(issuerCertificate.getEncoded()), subjectSerialNumber);

        // generate the request
        final OCSPReqBuilder requestGenerator = new OCSPReqBuilder();
        requestGenerator.addRequest(certificateId);

        // Create a nonce to avoid replay attack
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true,
                new DEROctetString(nonce.toByteArray()));
        requestGenerator.setRequestExtensions(new Extensions(new Extension[] { ext }));

        final OCSPReq ocspRequest = requestGenerator.build();

        // perform the request
        final ClientResponse response = getClientResponse(ocspRequest);

        // ensure the request was completed successfully
        if (ClientResponse.Status.OK.getStatusCode() != response.getStatusInfo().getStatusCode()) {
            logger.warn(String.format("OCSP request was unsuccessful (%s).", response.getStatus()));
            return ocspStatus;
        }

        // interpret the response
        OCSPResp ocspResponse = new OCSPResp(response.getEntityInputStream());

        // verify the response status
        switch (ocspResponse.getStatus()) {
        case OCSPRespBuilder.SUCCESSFUL:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Successful);
            break;
        case OCSPRespBuilder.INTERNAL_ERROR:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.InternalError);
            break;
        case OCSPRespBuilder.MALFORMED_REQUEST:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.MalformedRequest);
            break;
        case OCSPRespBuilder.SIG_REQUIRED:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.SignatureRequired);
            break;
        case OCSPRespBuilder.TRY_LATER:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.TryLater);
            break;
        case OCSPRespBuilder.UNAUTHORIZED:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unauthorized);
            break;
        default:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unknown);
            break;
        }

        // only proceed if the response was successful
        if (ocspResponse.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
            logger.warn(String.format("OCSP request was unsuccessful (%s).",
                    ocspStatus.getResponseStatus().toString()));
            return ocspStatus;
        }

        // ensure the appropriate response object
        final Object ocspResponseObject = ocspResponse.getResponseObject();
        if (ocspResponseObject == null || !(ocspResponseObject instanceof BasicOCSPResp)) {
            logger.warn(String.format("Unexpected OCSP response object: %s", ocspResponseObject));
            return ocspStatus;
        }

        // get the response object
        final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) ocspResponse.getResponseObject();

        // attempt to locate the responder certificate
        final X509CertificateHolder[] responderCertificates = basicOcspResponse.getCerts();
        if (responderCertificates.length != 1) {
            logger.warn(String.format("Unexpected number of OCSP responder certificates: %s",
                    responderCertificates.length));
            return ocspStatus;
        }

        // get the responder certificate
        final X509Certificate trustedResponderCertificate = getTrustedResponderCertificate(
                responderCertificates[0], issuerCertificate);
        if (trustedResponderCertificate != null) {
            // verify the response
            if (basicOcspResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC")
                    .build(trustedResponderCertificate.getPublicKey()))) {
                ocspStatus.setVerificationStatus(VerificationStatus.Verified);
            } else {
                ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
            }
        } else {
            ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
        }

        // validate the response
        final SingleResp[] responses = basicOcspResponse.getResponses();
        for (SingleResp singleResponse : responses) {
            final CertificateID responseCertificateId = singleResponse.getCertID();
            final BigInteger responseSerialNumber = responseCertificateId.getSerialNumber();

            if (responseSerialNumber.equals(subjectSerialNumber)) {
                Object certStatus = singleResponse.getCertStatus();

                // interpret the certificate status
                if (CertificateStatus.GOOD == certStatus) {
                    ocspStatus.setValidationStatus(ValidationStatus.Good);
                } else if (certStatus instanceof RevokedStatus) {
                    ocspStatus.setValidationStatus(ValidationStatus.Revoked);
                } else {
                    ocspStatus.setValidationStatus(ValidationStatus.Unknown);
                }
            }
        }
    } catch (final OCSPException | IOException | UniformInterfaceException | ClientHandlerException
            | OperatorCreationException e) {
        logger.error(e.getMessage(), e);
    } catch (CertificateException e) {
        e.printStackTrace();
    }

    return ocspStatus;
}