Example usage for java.security.cert X509Certificate getNotAfter

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

Introduction

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

Prototype

public abstract Date getNotAfter();

Source Link

Document

Gets the notAfter date from the validity period of the certificate.

Usage

From source file:net.maritimecloud.identityregistry.controllers.BaseControllerWithCertificate.java

protected PemCertificate issueCertificate(CertificateModel certOwner, Organization org, String type,
        HttpServletRequest request) throws McBasicRestException {
    // Generate keypair for user
    KeyPair userKeyPair = CertificateUtil.generateKeyPair();
    // Find special MC attributes to put in the certificate
    HashMap<String, String> attrs = getAttr(certOwner);

    String o = org.getMrn();/*from  w w w  .jav a2  s .c  o m*/
    String name = getName(certOwner);
    String email = getEmail(certOwner);
    String uid = getUid(certOwner);
    if (uid == null || uid.trim().isEmpty()) {
        throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.ENTITY_ORG_ID_MISSING,
                request.getServletPath());
    }
    BigInteger serialNumber = certUtil.generateSerialNumber();
    X509Certificate userCert = certUtil.generateCertForEntity(serialNumber, org.getCountry(), o, type, name,
            email, uid, userKeyPair.getPublic(), attrs);
    String pemCertificate;
    try {
        pemCertificate = CertificateUtil.getPemFromEncoded("CERTIFICATE", userCert.getEncoded()).replace("\n",
                "\\n");
    } catch (CertificateEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    String pemPublicKey = CertificateUtil.getPemFromEncoded("PUBLIC KEY", userKeyPair.getPublic().getEncoded())
            .replace("\n", "\\n");
    String pemPrivateKey = CertificateUtil
            .getPemFromEncoded("PRIVATE KEY", userKeyPair.getPrivate().getEncoded()).replace("\n", "\\n");
    PemCertificate ret = new PemCertificate(pemPrivateKey, pemPublicKey, pemCertificate);

    // Create the certificate
    Certificate newMCCert = new Certificate();
    certOwner.assignToCert(newMCCert);
    newMCCert.setCertificate(pemCertificate);
    newMCCert.setSerialNumber(serialNumber);
    // The dates we extract from the cert is in localtime, so they are converted to UTC before saving into the DB
    Calendar cal = Calendar.getInstance();
    long offset = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET);
    newMCCert.setStart(new Date(userCert.getNotBefore().getTime() - offset));
    newMCCert.setEnd(new Date(userCert.getNotAfter().getTime() - offset));
    this.certificateService.saveCertificate(newMCCert);
    return ret;
}

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

/**
 * Sets the input for this composite. /* w w  w . ja  va 2 s .c  o 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:org.apigw.authserver.web.controller.ApplicationManagementController.java

private Certificate createCertificate(MultipartFile certificate, BindingResult result) {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Certificate cert = new Certificate();
    if (certificate != null && certificate.getSize() > 0) {

        try {//  w w  w . j a v a  2 s  . c  om
            PEMReader r = new PEMReader(
                    new InputStreamReader(new ByteArrayInputStream(certificate.getBytes())));
            Object certObj = r.readObject();

            long reference = System.currentTimeMillis();

            // validate certificate
            if (certObj instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) certObj;
                BigInteger serialNumber = x509cert.getSerialNumber();

                String issuerDn = x509cert.getIssuerDN().getName();
                String subjectDn = x509cert.getSubjectDN().getName();

                cert.setCertificate(certificate.getBytes());
                cert.setSerialNumber(serialNumber.toString());
                cert.setIssuer(issuerDn);
                cert.setSubject(subjectDn);
                cert.setSubjectCommonName(extractFromDn(subjectDn, "CN"));
                cert.setSubjectOrganization(extractFromDn(subjectDn, "O"));
                cert.setSubjectOrganizationUnit(extractFromDn(subjectDn, "OU"));
                cert.setSubjectLocation(extractFromDn(subjectDn, "L"));
                cert.setSubjectCountry(extractFromDn(subjectDn, "C"));
                cert.setNotAfter(x509cert.getNotAfter());
                cert.setNotBefore(x509cert.getNotBefore());
            } else {
                String line;
                StringBuilder certString = new StringBuilder();
                while ((line = r.readLine()) != null) {
                    certString.append(line + "\n");
                }
                log.warn(
                        "Bad certificate [{}]: Provided certificate was of the wrong type: {}. Certificate: \n{}",
                        new Object[] { reference, certObj, certString.toString() });
                result.rejectValue("certificates", "invalid.certificate",
                        "Certifikatet r ej giltigt (Reference: " + reference + ")");
            }

            r.close();
        } catch (IOException e) {
            log.warn("Bad certificate");
            result.rejectValue("certificates", "invalid.certificate", "Certifikatet r ej giltigt ");
        }
    }
    return cert;
}

From source file:org.signserver.client.cli.validationservice.ValidateCertificateCommand.java

private int run() throws Exception {

    // read certificate
    X509Certificate cert = null;
    FileInputStream fis = new FileInputStream(certPath);
    try {//from  w  w  w  .j a va2s  .co m
        if (pemFlag) {
            Collection<?> certs = CertTools.getCertsFromPEM(fis);
            if (certs.iterator().hasNext()) {
                cert = (X509Certificate) certs.iterator().next();
            }
        } else {
            byte[] data = new byte[fis.available()];
            fis.read(data, 0, fis.available());
            cert = (X509Certificate) CertTools.getCertfromByteArray(data);
        }
    } finally {
        fis.close();
    }

    if (cert == null) {
        println("Error, Certificate in file " + certPath + " not read succesfully.");
    }

    println("\n\nValidating certificate with: ");
    println("  Subject    : " + cert.getSubjectDN().toString());
    println("  Issuer     : " + cert.getIssuerDN().toString());
    println("  Valid From : " + cert.getNotBefore());
    println("  Valid To   : " + cert.getNotAfter());

    println("\n");

    // validate
    final ValidateResponse vresp;
    switch (protocol) {
    case WEBSERVICES:
        // set up trust
        SSLSocketFactory sslf = null;
        if (trustStorePath != null) {
            sslf = WSClientUtil.genCustomSSLSocketFactory(null, null, trustStorePath, trustStorePwd);
        }

        vresp = runWS(sslf, cert);
        break;
    case HTTP:
        vresp = runHTTP(cert);
        break;
    default:
        throw new IllegalArgumentException("Unknown protocol: " + protocol.toString());
    }
    ;

    // output result
    String certificatePurposes = vresp.getValidCertificatePurposes();
    println("Valid Certificate Purposes:\n  " + (certificatePurposes == null ? "" : certificatePurposes));
    Validation validation = vresp.getValidation();
    println("Certificate Status:\n  " + validation.getStatus());

    return getReturnValue(validation.getStatus());
}

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

/**
 * Produce a human readable export of the given tsl to the given file.
 * /*from   www  . j  a v  a 2  s .com*/
 * @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:com.idevity.card.read.ShowCHUID.java

/**
 * Method onCreateView.//from w w  w.j a  va  2  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();
    String issuer = new String();
    String subject = new String();
    String validfrom = new String();
    String validto = new String();
    boolean certvalid = true;
    boolean sigvalid = false;
    CMSSignedDataObject chuidSig = null;
    X509Certificate pcs = null;

    View chuidLayout = inflater.inflate(R.layout.activity_show_chuid, container, false);
    // get card data

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

    // get chuid
    PIVCardHolderUniqueID chuid = null;
    PIVDataTempl chuidInDataTempl = carddata.getPIVCardHolderUniqueID();
    if (chuidInDataTempl != null) {
        byte[] chuidData = chuidInDataTempl.getData();
        if (chuidData == null) {
            chuidData = chuidInDataTempl.getEncoded();
        }
        chuid = new PIVCardHolderUniqueID(chuidData);
    }
    if (chuid != null) {
        try {
            // get chuid signature object
            chuidSig = new CMSSignedDataObject(chuid.getSignatureBytes(), chuid.getSignatureDataBytes());
            chuidSig.setProviderName("OpenSSLFIPSProvider");
            // validate the signature, don't do PDVAL
            sigvalid = chuidSig.verifySignature(false);
        } catch (SignatureException e) {
            Log.e(TAG, "Error: " + e.getMessage());
        }
        // get x509 cert
        if (chuidSig != null) {
            pcs = chuidSig.getSigner();
        }
        // get values from x509
        if (pcs != null) {
            issuer = pcs.getIssuerDN().getName();
            subject = pcs.getSubjectDN().getName();
            validfrom = pcs.getNotBefore().toString();
            validto = pcs.getNotAfter().toString();
        }

    }

    ImageView sigthumbs = (ImageView) chuidLayout.findViewById(R.id.chuidindicator1);
    TextView sigtext = (TextView) chuidLayout.findViewById(R.id.chuid1);
    if (sigvalid) {
        sigthumbs.setImageResource(R.drawable.cert_good);
    } else {
        sigthumbs.setImageResource(R.drawable.cert_bad);
        sigtext.setTextColor(getResources().getColor(R.color.idredmain));
    }

    /*
     * Note to self. I am not thrilled how Java almost forces you to assume
     * a certificate if valid unless an exception is thrown!
     */
    TextView vfText = (TextView) chuidLayout.findViewById(R.id.chuid4);
    TextView vtText = (TextView) chuidLayout.findViewById(R.id.chuid5);

    try {
        if (pcs != null) {
            pcs.checkValidity();
        }
    } catch (CertificateNotYetValidException e) {
        certvalid = false;
        vfText.setTextColor(getResources().getColor(R.color.idredmain));
        if (debug) {
            Log.d(TAG, "Error: Authentication Certificate Not Vaid Yet!");
        }
    } catch (CertificateExpiredException e) {
        certvalid = false;
        vtText.setTextColor(getResources().getColor(R.color.idredmain));
        if (debug) {
            Log.d(TAG, "Error: Card Authentication Certificate Expired!");
        }
    }
    ImageView certthumbs = (ImageView) chuidLayout.findViewById(R.id.chuidindicator2);
    TextView certtext = (TextView) chuidLayout.findViewById(R.id.chuid2);
    if (certvalid && pcs != null) {
        certthumbs.setImageResource(R.drawable.cert_good);
    } else {
        certthumbs.setImageResource(R.drawable.cert_bad);
        certtext.setTextColor(getResources().getColor(R.color.idredmain));
    }

    // setting all values in activity
    TextView editChuidSubject = (TextView) chuidLayout.findViewById(R.id.chuid_subject);
    editChuidSubject.setText(subject);

    TextView editValidFrom = (TextView) chuidLayout.findViewById(R.id.chuid_date);
    editValidFrom.setText(validfrom);

    TextView editValidTo = (TextView) chuidLayout.findViewById(R.id.chuid_expiry);
    editValidTo.setText(validto);

    TextView editIssuer = (TextView) chuidLayout.findViewById(R.id.chuid_issuer);
    editIssuer.setText(issuer);

    return chuidLayout;
}

From source file:be.fedict.trust.service.bean.DownloaderMDB.java

private void processColdStartMessage(ColdStartMessage coldStartMessage) {
    if (null == coldStartMessage) {
        return;//w  w w . ja v a  2s .  c o  m
    }

    String crlUrl = coldStartMessage.getCrlUrl();
    String certUrl = coldStartMessage.getCertUrl();
    LOG.debug("cold start CRL URL: " + crlUrl);
    LOG.debug("cold start CA URL: " + certUrl);

    File crlFile = download(crlUrl);
    File certFile = download(certUrl);

    // parsing
    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        LOG.debug("certificate factory error: " + e.getMessage(), e);
        crlFile.delete();
        certFile.delete();
        return;
    }

    X509Certificate certificate = null;
    try {
        certificate = (X509Certificate) certificateFactory.generateCertificate(new FileInputStream(certFile));
    } catch (Exception e) {
        LOG.debug("error DER-parsing certificate");
        try {
            PEMReader pemReader = new PEMReader(new FileReader(certFile));
            certificate = (X509Certificate) pemReader.readObject();
            pemReader.close();
        } catch (Exception e2) {
            retry("error PEM-parsing certificate", e, certFile, crlFile);
        }
    }
    certFile.delete();

    X509CRL crl = null;
    try {
        crl = (X509CRL) certificateFactory.generateCRL(new FileInputStream(crlFile));
    } catch (Exception e) {
        retry("error parsing CRL", e, crlFile);
    }

    // first check whether the two correspond
    try {
        crl.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.error("no correspondence between CRL and CA");
        LOG.error("CRL issuer: " + crl.getIssuerX500Principal());
        LOG.debug("CA subject: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }
    LOG.debug("CRL matches CA: " + certificate.getSubjectX500Principal());

    // skip expired CAs
    Date now = new Date();
    Date notAfter = certificate.getNotAfter();
    if (now.after(notAfter)) {
        LOG.warn("CA already expired: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }

    // create database entitities
    CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(certificate);
    if (null != certificateAuthority) {
        LOG.debug("CA already in cache: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }

    /*
     * Lookup Root CA's trust point via parent certificates' CA entity.
     */
    LOG.debug(
            "Lookup Root CA's trust point via parent certificates' CA entity - Don't have Issuer's Serial Number??");
    String parentIssuerName = certificate.getIssuerX500Principal().toString();
    CertificateAuthorityEntity parentCertificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(parentIssuerName);
    if (null == parentCertificateAuthority) {
        LOG.error("CA not found for " + parentIssuerName + " ?!");
        crlFile.delete();
        return;
    }
    LOG.debug("parent CA: " + parentCertificateAuthority.getName());
    TrustPointEntity parentTrustPoint = parentCertificateAuthority.getTrustPoint();
    if (null != parentTrustPoint) {
        LOG.debug("trust point parent: " + parentTrustPoint.getName());
        LOG.debug("previous trust point fire data: " + parentTrustPoint.getFireDate());
    } else {
        LOG.debug("no parent trust point");
    }

    // create new CA
    certificateAuthority = this.certificateAuthorityDAO.addCertificateAuthority(certificate, crlUrl);

    // prepare harvesting
    certificateAuthority.setTrustPoint(parentTrustPoint);
    certificateAuthority.setStatus(Status.PROCESSING);
    if (null != certificateAuthority.getTrustPoint()
            && null == certificateAuthority.getTrustPoint().getFireDate()) {
        try {
            this.schedulingService.startTimer(certificateAuthority.getTrustPoint());
        } catch (InvalidCronExpressionException e) {
            LOG.error("invalid cron expression");
            crlFile.delete();
            return;
        }
    }

    // notify harvester
    String crlFilePath = crlFile.getAbsolutePath();
    try {
        this.notificationService.notifyHarvester(certificate.getSubjectX500Principal().toString(), crlFilePath,
                false);
    } catch (JMSException e) {
        crlFile.delete();
        throw new RuntimeException(e);
    }
}

From source file:com.idevity.card.read.ShowCert.java

/**
 * Method onCreateView./*w w w. j a  va  2  s  . co  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:homenetapp.HomeNetAppGui.java

private void checkClientCert() {
    try {/*from w  w  w .  j a  v  a2 s  .co m*/
        URL url = new URL("https://" + homenetapp.clientServer + "/");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.connect();
        Certificate[] certs = conn.getServerCertificates();

        //System.out.println("Cert Chain Length: "+certs.length);

        Certificate c = certs[0];
        X509Certificate xc = (X509Certificate) c;

        String[] from = homenetapp.splitTokens(xc.getIssuerX500Principal().getName(), "=, ");
        String[] to = homenetapp.splitTokens(xc.getSubjectX500Principal().getName(), "=, ");

        certPropertiesLabel.setText("<html>Issued by: " + from[1] + "<br>For: " + to[1] + "<br>Expires: "
                + xc.getNotAfter() + "</html>");

        System.out.println("Cert: " + c.getType());

        System.out.println("Not After: " + xc.getNotAfter());
        System.out.println("Subject DN: " + xc.getSubjectX500Principal());
        System.out.println("Issuer DN: " + xc.getIssuerX500Principal());
        System.out.println("getSigAlgName: " + xc.getSigAlgName());

    } catch (Exception e) {
        certPropertiesLabel.setText("Failed to load certficate");
    }

}