Example usage for java.security DigestInputStream DigestInputStream

List of usage examples for java.security DigestInputStream DigestInputStream

Introduction

In this page you can find the example usage for java.security DigestInputStream DigestInputStream.

Prototype

public DigestInputStream(InputStream stream, MessageDigest digest) 

Source Link

Document

Creates a digest input stream, using the specified input stream and message digest.

Usage

From source file:edu.usu.sdl.openstorefront.service.io.HelpImporter.java

@Override
public void initialize() {
    try {/* w w  w  .j av a 2s  .  c  o m*/

        ServiceProxy serviceProxy = new ServiceProxy();

        //Check for file changes
        MessageDigest md = MessageDigest.getInstance("MD5");
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        try (InputStream is = HelpImporter.class.getResourceAsStream("/userhelp.md");
                DigestInputStream dis = new DigestInputStream(is, md);) {
            FileSystemManager.copy(dis, bout);
        }
        byte[] digest = md.digest();
        String checkSum = serviceProxy.getSystemService().getPropertyValue(ApplicationProperty.HELP_SYNC);

        boolean process = true;
        String newCheckSum = new String(digest);
        if (StringUtils.isNotBlank(checkSum)) {
            if (checkSum.equals(newCheckSum)) {
                process = false;
            }
        }

        if (process) {
            log.log(Level.INFO, "Loading Help");
            List<HelpSection> helpSections = processHelp(new ByteArrayInputStream(bout.toByteArray()));
            serviceProxy.getSystemService().loadNewHelpSections(helpSections);

            serviceProxy.getSystemService().saveProperty(ApplicationProperty.HELP_SYNC, newCheckSum);
            log.log(Level.INFO, "Done Loading Help");
        }

    } catch (NoSuchAlgorithmException | IOException ex) {
        throw new OpenStorefrontRuntimeException("Unable to load help.",
                "Check system and resource userhelp.md", ex);
    }
}

From source file:jobhunter.persistence.Persistence.java

private Optional<Profile> _readProfile(final File file) {

    try (ZipFile zfile = new ZipFile(file)) {
        l.debug("Reading profile from JHF File");
        final InputStream in = zfile.getInputStream(new ZipEntry("profile.xml"));

        MessageDigest md = MessageDigest.getInstance("MD5");
        DigestInputStream dis = new DigestInputStream(in, md);

        final Object obj = xstream.fromXML(dis);

        updateLastMod(file, md);/*from   w w  w .  java  2  s.  co m*/

        return Optional.of((Profile) obj);
    } catch (Exception e) {
        l.error("Failed to read file: {}", e.getMessage());
    }

    return Optional.empty();
}

From source file:com.stimulus.archiva.domain.EmailID.java

public static synchronized String generateUniqueID(Email email) {
    try {//from   ww w.  j  av  a2 s  .c o  m
        MimeMessage raw = email;
        // we need a backup plan here
        if (raw == null) {
            return DateUtil.convertDatetoString(new Date());
        }
        Enumeration<Header> headers = raw.getAllHeaders();
        LinkedList<String> orderedHeaders = new LinkedList<String>();
        while (headers.hasMoreElements()) {
            Header header = headers.nextElement();

            if (Compare.equalsIgnoreCase(header.getName(), "Date")
                    || Compare.equalsIgnoreCase(header.getName(), "CC")
                    || Compare.equalsIgnoreCase(header.getName(), "BCC")
                    || Compare.equalsIgnoreCase(header.getName(), "Subject")
                    || Compare.equalsIgnoreCase(header.getName(), "To")
                    || Compare.equalsIgnoreCase(header.getName(), "From"))
                orderedHeaders.add(header.getName() + header.getValue());

        }
        Collections.sort(orderedHeaders);
        StringBuffer allHeaders = new StringBuffer();
        for (String header : orderedHeaders)
            allHeaders.append(header);
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] bytes = allHeaders.toString().getBytes();
        InputStream is = new ByteArrayInputStream(bytes);
        DigestInputStream dis = new DigestInputStream(is, sha);
        while (dis.read() != -1)
            ;
        dis.close();
        byte[] digest = sha.digest();
        return toHex(digest);
    } catch (Exception e) {
        logger.error("failed to generate a uniqueid for a message");
        return null;
    }
}

From source file:com.thoughtworks.go.agent.launcher.ServerBinaryDownloaderTest.java

@Test
public void shouldSetMd5AndSSLPortHeaders() throws Exception {
    ServerBinaryDownloader downloader = new ServerBinaryDownloader(
            ServerUrlGeneratorMother.generatorFor("localhost", server.getPort()), null,
            SslVerificationMode.NONE);/*  www .j a v a  2  s  .  c  o m*/
    downloader.downloadIfNecessary(DownloadableFile.AGENT);

    MessageDigest digester = MessageDigest.getInstance("MD5");
    try (BufferedInputStream stream = new BufferedInputStream(
            new FileInputStream(DownloadableFile.AGENT.getLocalFile()))) {
        try (DigestInputStream digest = new DigestInputStream(stream, digester)) {
            IOUtils.copy(digest, new NullOutputStream());
        }
        assertThat(downloader.getMd5(), is(Hex.encodeHexString(digester.digest()).toLowerCase()));
    }
}

From source file:com.quartz.AmazonQuartzJob.java

/**
 * Calculate content MD5 header values for feeds stored on disk.
 *//*from w  w  w  .jav a2s .  c om*/
public String computeContentMD5HeaderValue(FileInputStream fis) throws IOException, NoSuchAlgorithmException {
    DigestInputStream dis = new DigestInputStream(fis, MessageDigest.getInstance("MD5"));
    byte[] buffer = new byte[8192];
    while (dis.read(buffer) > 0)
        ;
    String md5Content = new String(
            org.apache.commons.codec.binary.Base64.encodeBase64(dis.getMessageDigest().digest()));
    // Effectively resets the stream to be beginning of the file
    // via a FileChannel.
    fis.getChannel().position(0);
    return md5Content;
}

From source file:de.elomagic.carafile.server.bl.SeedBean.java

public MetaData seedFile(final InputStream inputStream, final String filename)
        throws IOException, GeneralSecurityException, JMSException {
    LOG.debug("Seeding file " + filename);
    MetaData md;/*from   w  w  w  .j ava 2s .co m*/
    md = new MetaData();
    md.setFilename(filename);
    md.setCreationDate(new Date());
    md.setChunkSize(DEFAULT_PIECE_SIZE);
    md.setRegistryURI(UriBuilder.fromUri(registryURI).build());

    MessageDigest messageDigest = DigestUtils.getSha1Digest();
    long totalBytes = 0;

    try (DigestInputStream dis = new DigestInputStream(inputStream, messageDigest)) {
        byte[] buffer = new byte[md.getChunkSize()];
        int bytesRead;
        while ((bytesRead = readBlock(dis, buffer)) > 0) {
            totalBytes += bytesRead;
            String chunkId = Hex
                    .encodeHexString(DigestUtils.sha1(new ByteArrayInputStream(buffer, 0, bytesRead)));

            repositoryBean.writeChunk(chunkId, buffer, bytesRead);

            URI uri = UriBuilder.fromUri(ownURI).build();

            ChunkData chunkData = new ChunkData(chunkId, uri);
            md.addChunk(chunkData);
        }
    }

    md.setSize(totalBytes);
    md.setId(Hex.encodeHexString(messageDigest.digest()));

    LOG.debug("File id of seed file is " + md.getId() + "; Size=" + md.getSize() + "; Chunks="
            + md.getChunks().size());

    // Initiate to register at tracker
    LOG.debug("Queue up new file for registration.");
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer messageProducer = session.createProducer(fileQueue);

    ObjectMessage message = session.createObjectMessage(md);

    messageProducer.send(message);

    connection.close();

    return md;
}

From source file:com.docdoku.cli.helpers.FileHelper.java

public String downloadFile(File pLocalFile, String pURL)
        throws IOException, LoginException, NoSuchAlgorithmException {
    ConsoleProgressMonitorInputStream in = null;
    OutputStream out = null;//w  w w . j  a  va 2 s .  c o  m
    HttpURLConnection conn = null;
    try {
        //Hack for NTLM proxy
        //perform a head method to negociate the NTLM proxy authentication
        URL url = new URL(pURL);
        System.out.println("Downloading file: " + pLocalFile.getName() + " from " + url.getHost());
        performHeadHTTPMethod(url);

        out = new BufferedOutputStream(new FileOutputStream(pLocalFile), BUFFER_CAPACITY);

        conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestMethod("GET");
        byte[] encoded = Base64.encodeBase64((login + ":" + password).getBytes("ISO-8859-1"));
        conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII"));
        conn.connect();
        manageHTTPCode(conn);

        MessageDigest md = MessageDigest.getInstance("MD5");
        in = new ConsoleProgressMonitorInputStream(conn.getContentLength(),
                new DigestInputStream(new BufferedInputStream(conn.getInputStream(), BUFFER_CAPACITY), md));
        byte[] data = new byte[CHUNK_SIZE];
        int length;

        while ((length = in.read(data)) != -1) {
            out.write(data, 0, length);
        }
        out.flush();

        byte[] digest = md.digest();
        return Base64.encodeBase64String(digest);
    } finally {
        if (out != null)
            out.close();
        if (in != null)
            in.close();
        if (conn != null)
            conn.disconnect();
    }
}

From source file:org.panbox.linux.desktop.identitymgmt.TestDownloadHashCompare.java

/**
 * Creates a Hash value for a given file
 * @param file/*from  www .ja  v a  2 s  . c o m*/
 * @return
 */
private byte[] createFileHash(File file) {
    MessageDigest md = null;
    try (InputStream is = Files.newInputStream(Paths.get(file.getAbsolutePath()))) {

        md = MessageDigest.getInstance("SHA-256");
        DigestInputStream dis = new DigestInputStream(is, md);

        /* Read stream to EOF as normal... */

        while (dis.available() > 0) {
            dis.read();
        }

    } catch (NoSuchAlgorithmException e) {
        fail();
    } catch (IOException e1) {
        fail();
    }
    byte[] digest = md.digest();

    //String h = Hex.encodeHexString( digest );

    return digest;
}

From source file:org.atombeat.xquery.functions.util.CopyFile.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    // try to copy 
    try {//from  w  ww  .j  a  v a 2  s .co  m
        String from = args[0].getStringValue();
        String to = args[1].getStringValue();
        File fromFile = new File(from);
        File toFile = new File(to);

        InputStream in = new FileInputStream(fromFile);
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        in = new DigestInputStream(in, md5);
        OutputStream out = new FileOutputStream(toFile);

        Stream.copy(in, out);

        String signature = new BigInteger(1, md5.digest()).toString(16);
        return new StringValue(signature);

    } catch (IOException ioe) {
        throw new XPathException(this, "An IO exception ocurred: " + ioe.getMessage(), ioe);
    } catch (NoSuchAlgorithmException e) {
        throw new XPathException(this, "A message digest exception ocurred: " + e.getMessage(), e);
    }

}

From source file:jobhunter.persistence.Persistence.java

private Optional<List<Subscription>> _readSubscriptions(final File file) {

    try (ZipFile zfile = new ZipFile(file)) {
        l.debug("Reading subscriptions from JHF File");
        final InputStream in = zfile.getInputStream(new ZipEntry("subscriptions.xml"));

        MessageDigest md = MessageDigest.getInstance("MD5");
        DigestInputStream dis = new DigestInputStream(in, md);

        final Object obj = xstream.fromXML(dis);

        updateLastMod(file, md);//from  w  w  w.j  a v a 2 s .c om

        return Optional.of(cast(obj));
    } catch (Exception e) {
        l.error("Failed to read file: {}", e.getMessage());
    }

    return Optional.empty();
}