Example usage for java.security.cert X509Certificate getNotBefore

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

Introduction

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

Prototype

public abstract Date getNotBefore();

Source Link

Document

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

Usage

From source file:org.apache.jmeter.protocol.http.proxy.JMeterProxyControl.java

public String[] getCertificateDetails() {
    if (isDynamicMode()) {
        try {//from w  w  w  .  j a v  a  2 s  .  c om
            X509Certificate caCert = (X509Certificate) sslKeyStore
                    .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: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();/* www . java2  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. /*ww 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:be.fedict.eid.tsl.Tsl2PdfExporter.java

/**
 * Produce a human readable export of the given tsl to the given file.
 * /* w w  w.j a v  a2s .  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.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. ja  va  2  s  .  c o 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: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 {/*from   w  ww  .  j  a v a  2s . 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:com.idevity.card.read.ShowCHUID.java

/**
 * Method onCreateView.//from   w  ww  .ja  v a2s  .  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.PublicKeyTrustLinker.java

public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData) {
    if (false == childCertificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) {
        LOG.debug("child certificate issuer not the same as the issuer certificate subject");
        LOG.debug("child certificate: " + childCertificate.getSubjectX500Principal());
        LOG.debug("certificate: " + certificate.getSubjectX500Principal());
        LOG.debug("child certificate issuer: " + childCertificate.getIssuerX500Principal());
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                "child certificate issuer not the same as the issuer certificate subject");
    }/*from  w ww .  java 2s  .  co  m*/
    try {
        childCertificate.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.debug("verification error: " + e.getMessage(), e);
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE,
                "verification error: " + e.getMessage());
    }
    if (true == childCertificate.getNotAfter().after(certificate.getNotAfter())) {
        LOG.warn("child certificate validity end is after certificate validity end");
        LOG.warn("child certificate validity end: " + childCertificate.getNotAfter());
        LOG.warn("certificate validity end: " + certificate.getNotAfter());
    }
    if (true == childCertificate.getNotBefore().before(certificate.getNotBefore())) {
        LOG.warn("child certificate validity begin before certificate validity begin");
        LOG.warn("child certificate validity begin: " + childCertificate.getNotBefore());
        LOG.warn("certificate validity begin: " + certificate.getNotBefore());
    }
    if (true == validationDate.before(childCertificate.getNotBefore())) {
        LOG.debug("certificate is not yet valid");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate is not yet valid");
    }
    if (true == validationDate.after(childCertificate.getNotAfter())) {
        LOG.debug("certificate already expired");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate already expired");
    }
    if (-1 == certificate.getBasicConstraints()) {
        LOG.debug("certificate not a CA");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "certificate not a CA");
    }
    if (0 == certificate.getBasicConstraints() && -1 != childCertificate.getBasicConstraints()) {
        LOG.debug("child should not be a CA");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "child should not be a CA");
    }

    /*
     * SKID/AKID sanity check
     */
    boolean isCa = isCa(certificate);
    boolean isChildCa = isCa(childCertificate);

    byte[] subjectKeyIdentifierData = certificate
            .getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
    byte[] authorityKeyIdentifierData = childCertificate
            .getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());

    if (isCa && null == subjectKeyIdentifierData) {
        LOG.debug("certificate is CA and MUST contain a Subject Key Identifier");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                "certificate is CA and  MUST contain a Subject Key Identifier");
    }

    if (isChildCa && null == authorityKeyIdentifierData) {
        LOG.debug("child certificate is CA and MUST contain an Authority Key Identifier");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                "child certificate is CA and MUST contain an Authority Key Identifier");
    }

    if (null != subjectKeyIdentifierData && null != authorityKeyIdentifierData) {

        AuthorityKeyIdentifierStructure authorityKeyIdentifierStructure;
        try {
            authorityKeyIdentifierStructure = new AuthorityKeyIdentifierStructure(authorityKeyIdentifierData);
        } catch (IOException e) {
            LOG.debug("Error parsing authority key identifier structure");
            return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                    "Error parsing authority key identifier structure");
        }
        String akidId = new String(Hex.encodeHex(authorityKeyIdentifierStructure.getKeyIdentifier()));

        SubjectKeyIdentifierStructure subjectKeyIdentifierStructure;
        try {
            subjectKeyIdentifierStructure = new SubjectKeyIdentifierStructure(subjectKeyIdentifierData);
        } catch (IOException e) {
            LOG.debug("Error parsing subject key identifier structure");
            return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                    "Error parsing subject key identifier structure");
        }
        String skidId = new String(Hex.encodeHex(subjectKeyIdentifierStructure.getKeyIdentifier()));

        if (!skidId.equals(akidId)) {
            LOG.debug(
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
            return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
        }
    }

    /*
     * We don't check pathLenConstraint since this one is only there to
     * protect the PKI business.
     */
    return null;
}

From source file:org.brekka.pegasus.core.services.impl.CertificateAuthenticationServiceImpl.java

@Override
@Transactional()/* ww  w.  j  av  a  2  s  .  c om*/
public DigitalCertificate authenticate(X509Certificate certificate)
        throws BadCredentialsException, DisabledException {
    byte[] signature = certificate.getSignature();
    String subjectDN = certificate.getSubjectDN().getName();
    String commonName = null;

    Matcher matcher = matchAllowedSubjectDN(subjectDN, allowedSubjectDistinguishedNamePatterns);
    if (matcher.groupCount() > 0) {
        commonName = matcher.group(1);
    }

    byte[] subjectDNBytes = subjectDN.getBytes(Charset.forName("UTF-8"));
    SystemDerivedKeySpecType spec = config.getSubjectDerivedKeySpec();

    DerivedKey derivedKey = derivedKeyCryptoService.apply(subjectDNBytes, spec.getSalt(), null,
            CryptoProfile.Static.of(spec.getCryptoProfile()));
    byte[] distinguishedNameDigest = derivedKey.getDerivedKey();
    CertificateSubject certificateSubject = certificateSubjectDAO
            .retrieveByDistinguishedNameDigest(distinguishedNameDigest);
    if (certificateSubject == null) {
        // Create it
        certificateSubject = new CertificateSubject();
        certificateSubject.setDistinguishedNameDigest(distinguishedNameDigest);
        certificateSubjectDAO.create(certificateSubject);
    }

    DigitalCertificate digitalCertificate = digitalCertificateDAO
            .retrieveBySubjectAndSignature(certificateSubject, signature);
    if (digitalCertificate == null) {
        digitalCertificate = new DigitalCertificate();
        digitalCertificate.setActive(Boolean.TRUE);
        digitalCertificate.setCertificateSubject(certificateSubject);
        digitalCertificate.setCreated(certificate.getNotBefore());
        digitalCertificate.setExpires(certificate.getNotAfter());
        digitalCertificate.setSignature(signature);
        digitalCertificateDAO.create(digitalCertificate);
    }

    // Perform some checks
    if (BooleanUtils.isNotTrue(digitalCertificate.getActive())) {
        throw new DisabledException(
                String.format("The certficate with id '%s' has been disabled", digitalCertificate.getId()));
    }
    if (digitalCertificate.getExpires().before(new Date())) {
        throw new CredentialsExpiredException(String.format("The certficate with id '%s' expired %tF",
                digitalCertificate.getId(), digitalCertificate.getExpires()));
    }

    // Both of these are transient
    certificateSubject.setCommonName(commonName);
    certificateSubject.setDistinguishedName(subjectDN);
    return digitalCertificate;
}