Example usage for org.apache.commons.codec.digest DigestUtils sha256Hex

List of usage examples for org.apache.commons.codec.digest DigestUtils sha256Hex

Introduction

In this page you can find the example usage for org.apache.commons.codec.digest DigestUtils sha256Hex.

Prototype

public static String sha256Hex(String data) 

Source Link

Usage

From source file:io.hops.hopsworks.common.dao.tensorflow.config.TensorBoardProcessMgr.java

/**
 * Cleanup the local TensorBoard directory
 * @param tb/*ww  w . j  a  v a  2s .c o  m*/
 * @throws IOException
 */
public void cleanupLocalTBDir(TensorBoard tb) throws ServiceException {

    int hdfsUserId = tb.getHdfsUserId();
    HdfsUsers hdfsUser = hdfsUsersFacade.findById(hdfsUserId);
    String tbBasePath = settings.getStagingDir() + Settings.TENSORBOARD_DIRS + File.separator;
    String projectUserUniquePath = tb.getProject().getName() + "_" + hdfsUser.getName();
    String tbPath = tbBasePath + DigestUtils.sha256Hex(projectUserUniquePath);

    //dematerialize certificates
    String certsPath = tbBasePath + DigestUtils.sha256Hex(projectUserUniquePath + "_certs");
    DistributedFileSystemOps dfso = dfsService.getDfsOps();
    try {
        HopsUtils.cleanupCertificatesForUserCustomDir(tb.getUsers().getUsername(), tb.getProject().getName(),
                settings.getHdfsTmpCertDir(), certificateMaterializer, certsPath, settings);
    } finally {
        if (dfso != null) {
            dfsService.closeDfsClient(dfso);
        }
    }

    //remove directory itself
    File tbDir = new File(tbPath);
    if (tbDir.exists()) {
        try {
            FileUtils.deleteDirectory(tbDir);
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Could not delete TensorBoard directory: " + tbDir);
            throw new ServiceException(RESTCodes.ServiceErrorCode.TENSORBOARD_CLEANUP_ERROR, Level.SEVERE,
                    "TensorBoard directory:" + tbDir, e.getMessage());
        }
    }
}

From source file:de.elomagic.maven.http.HTTPMojo.java

private void checkFile(final Path path) throws Exception {

    String fileDigest;//from   w  ww  .  j  a  v  a  2s  .  co  m

    try (InputStream in = Files.newInputStream(path)) {
        switch (digestType.toLowerCase()) {
        case "md5":
            fileDigest = DigestUtils.md5Hex(in);
            break;
        case "sha1":
            fileDigest = DigestUtils.sha1Hex(in);
            break;
        case "sha256":
            fileDigest = DigestUtils.sha256Hex(in);
            break;
        case "sha384":
            fileDigest = DigestUtils.sha384Hex(in);
            break;
        case "sha512":
            fileDigest = DigestUtils.sha512Hex(in);
            break;

        default:
            throw new Exception("Digest type \"" + digestType + "\" not supported.");
        }
    }

    if (!fileDigest.equalsIgnoreCase(digest)) {
        throw new Exception(
                digestType + " digest check failed. File=\"" + fileDigest + "\", Digest=\"" + digest + "\"");
    }

}

From source file:fi.vm.kapa.identification.adapter.service.SessionParserService.java

String createTupasVerificationMac(String version, String timestamp, String idNbr, String origStamp,
        String custName, String keyVers, String algorithm, String custId, String custType,
        String sharedSecret) {/*from   w  w w  .ja v  a  2s.co  m*/
    String tupasString = version + "&" + timestamp + "&" + idNbr + "&" + origStamp + "&" + custName + "&"
            + keyVers + "&" + algorithm + "&" + custId + "&" + custType + "&" + sharedSecret + "&";

    logger.debug("Generated Tupas response MAC string:\n{}", tupasString);

    try {
        return DigestUtils.sha256Hex(tupasString.getBytes("ISO-8859-1")).toUpperCase();
    } catch (UnsupportedEncodingException e) {
        logger.error("Unable to calculate tupas response verification MAC", e);
        return null;
    }
}

From source file:be.fedict.eid.tsl.tool.TslInternalFrame.java

@Override
public void valueChanged(TreeSelectionEvent event) {
    DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    if (treeNode.isLeaf()) {
        TrustService trustService = (TrustService) treeNode.getUserObject();
        this.serviceName.setText(trustService.getName());
        this.serviceType.setText(trustService.getType()
                .substring(trustService.getType().indexOf("Svctype/") + "Svctype/".length()));
        this.serviceStatus.setText(trustService.getStatus()
                .substring(trustService.getStatus().indexOf("Svcstatus/") + "Svcstatus/".length()));
        X509Certificate certificate = trustService.getServiceDigitalIdentity();
        byte[] encodedCertificate;
        try {// w  w  w.  jav  a 2  s .co m
            encodedCertificate = certificate.getEncoded();
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("cert: " + e.getMessage(), e);
        }
        String sha1Thumbprint = DigestUtils.shaHex(encodedCertificate);
        this.serviceSha1Thumbprint.setText(sha1Thumbprint);

        String sha256Thumbprint = DigestUtils.sha256Hex(encodedCertificate);
        this.serviceSha256Thumbprint.setText(sha256Thumbprint);

        this.validityBegin.setText(certificate.getNotBefore().toString());
        this.validityEnd.setText(certificate.getNotAfter().toString());
    } else {
        this.serviceName.setText("");
        this.serviceType.setText("");
        this.serviceStatus.setText("");
        this.serviceSha1Thumbprint.setText("");
        this.serviceSha256Thumbprint.setText("");
        this.validityBegin.setText("");
        this.validityEnd.setText("");
    }
}

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

/**
 * Produce a human readable export of the given tsl to the given file.
 * /* w  ww.j a v a2  s . c  om*/
 * @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:de.powerstaff.business.service.impl.WrongDataServiceImpl.java

private void processFiles(File aReportFile) {
    File theProfileDoppelterInhalt = new File(aReportFile, "Profile_doppelter_Inhalt.csv");

    PrintWriter theProfileDoppelterInhaltWriter = null;

    try {//from   www . ja v a 2  s.  com
        theProfileDoppelterInhaltWriter = new PrintWriter(theProfileDoppelterInhalt);

        theProfileDoppelterInhaltWriter.println("Dateinamen");

        Map<String, Set<File>> theHashes = new HashMap<String, Set<File>>();

        Set<String> theCodesFromFiles = new HashSet<String>();
        theCodesFromFiles.addAll(fsCache.getKnownCodes());

        for (String theCode : theCodesFromFiles) {
            Set<File> theFiles = fsCache.getFilesForCode(theCode);
            if (theFiles != null) {
                for (File theFile : theFiles) {
                    InputStream theStream = null;
                    try {
                        theStream = new FileInputStream(theFile);
                        String theHash = DigestUtils.sha256Hex(theStream);

                        Set<File> theFilesForHash = theHashes.get(theHash);
                        if (theFilesForHash == null) {
                            theFilesForHash = new HashSet<File>();
                            theHashes.put(theHash, theFilesForHash);
                        }
                        theFilesForHash.add(theFile);
                    } catch (Exception e) {
                        LOGGER.error("Error scanning file " + theFile, e);
                    } finally {
                        IOUtils.closeQuietly(theStream);
                    }
                }
            }
        }

        for (Map.Entry<String, Set<File>> theEntry : theHashes.entrySet()) {
            if (theEntry.getValue().size() > 1) {
                StringBuilder theBuilder = new StringBuilder();
                for (File theFile : theEntry.getValue()) {
                    if (theBuilder.length() > 0) {
                        theBuilder.append(";");
                    }
                    theBuilder.append(theFile.toString());
                }
                theProfileDoppelterInhaltWriter.println(theBuilder);
            }
        }

    } catch (Exception e) {
        LOGGER.error("Error processing files", e);
    } finally {
        IOUtils.closeQuietly(theProfileDoppelterInhaltWriter);
    }
}

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

/**
 * Produce a human readable export of the given tsl to the given file.
 * /* ww w.j  a va  2  s .  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:com.formkiq.core.service.FolderServiceImpl.java

/**
 * Generate SHA 256 for {@link FolderForm}.
 * @param user {@link User}//w ww .  j  a  v a2 s.c  o m
 * @param form {@link FolderForm}
 * @return {@link String}
 */
private String generateSha256(final User user, final FolderForm form) {

    SimpleDateFormat sdf = new SimpleDateFormat(JSONService.DEFAULT_DATE_FORMAT);

    String data = user.getEmail() + sdf.format(form.getUpdatedDate()) + form.getFolderid() + form.getUUID()
            + form.getData();

    String sha256hash = DigestUtils.sha256Hex(data);
    return sha256hash;
}

From source file:com.ning.maven.plugins.duplicatefinder.DuplicateFinderMojo.java

/**
 * Calculates the SHA256 Hash of a class in a file.
 * // ww w.ja v  a2 s  .c o m
 * @param file the archive contains the class
 * @param resourcePath the name of the class
 * @return the MD% Hash as Hex-Value
 * @throws IOException if any error occurs on reading class in archive
 */
private String getSHA256HexOfElement(final File file, final String resourcePath) throws IOException {
    class Sha256CacheKey {
        final File file;
        final String resourcePath;

        Sha256CacheKey(File file, String resourcePath) {
            this.file = file;
            this.resourcePath = resourcePath;
        }

        public boolean equals(Object o) {
            if (this == o)
                return true;
            if (o == null || getClass() != o.getClass())
                return false;

            Sha256CacheKey key = (Sha256CacheKey) o;

            return file.equals(key.file) && resourcePath.equals(key.resourcePath);
        }

        public int hashCode() {
            return 31 * file.hashCode() + resourcePath.hashCode();
        }
    }

    final Sha256CacheKey key = new Sha256CacheKey(file, resourcePath);
    if (CACHED_SHA256.containsKey(key)) {
        return (String) CACHED_SHA256.get(key);
    }

    ZipFile zip = new ZipFile(file);
    ZipEntry zipEntry = zip.getEntry(resourcePath);
    if (zipEntry == null) {
        throw new IOException("Could not found Zip-Entry for " + resourcePath + " in file " + file);
    }

    String sha256;

    InputStream in = zip.getInputStream(zipEntry);
    try {
        sha256 = DigestUtils.sha256Hex(in);
    } finally {
        IOUtils.closeQuietly(in);
    }

    CACHED_SHA256.put(key, sha256);

    return sha256;
}

From source file:de.fosd.jdime.artifact.file.FileArtifact.java

@Override
protected String hashId() {
    if (isFile()) {
        return DigestUtils.sha256Hex(file.getName() + getContent());
    } else {/*from  w  ww  . j  a v a 2s .com*/
        return DigestUtils.sha256Hex(file.getName());
    }
}