Example usage for java.security DigestInputStream read

List of usage examples for java.security DigestInputStream read

Introduction

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

Prototype

public int read(byte[] b, int off, int len) throws IOException 

Source Link

Document

Reads into a byte array, and updates the message digest (if the digest function is on).

Usage

From source file:MainClass.java

static void performInputTest() throws Exception {
    MessageDigest md = MessageDigest.getInstance("SHA");
    FileInputStream fin = new FileInputStream("sha-results.txt");
    DigestInputStream in = new DigestInputStream(fin, md);
    byte[] b = new byte["testCase".getBytes().length];
    in.read(b, 0, "testCase".getBytes().length);
    md = in.getMessageDigest();/*w w  w . j  a  v a 2  s . c om*/
    String s = new String(md.digest());
    System.out.println("Calculated result:  " + s);
}

From source file:MainClass.java

public static String md(String f) throws Exception {
    BufferedInputStream file = new BufferedInputStream(new FileInputStream(f));
    MessageDigest md = MessageDigest.getInstance("MD5");
    DigestInputStream in = new DigestInputStream(file, md);
    int i;/*from  w ww  .java 2 s  . c  om*/
    byte[] buffer = new byte[BUFFER_SIZE];
    do {
        i = in.read(buffer, 0, BUFFER_SIZE);
    } while (i == BUFFER_SIZE);
    md = in.getMessageDigest();
    in.close();

    return new String(md.digest());
}

From source file:MainClass.java

public static String md(String f) throws Exception {
    BufferedInputStream file = new BufferedInputStream(new FileInputStream(f));
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    DigestInputStream in = new DigestInputStream(file, md);
    int i;//from   www  .jav  a 2 s  . c  om
    byte[] buffer = new byte[BUFFER_SIZE];
    do {
        i = in.read(buffer, 0, BUFFER_SIZE);
    } while (i == BUFFER_SIZE);
    md = in.getMessageDigest();
    in.close();

    return new String(md.digest());
}

From source file:org.opf_labs.fmts.fidget.TikaIdentifier.java

static final String hash64K(final InputStream stream) throws IOException {
    SHA256.reset();/* w  w w  . j a va 2 s  .c  o  m*/
    // Create input streams for digest calculation
    DigestInputStream SHA256Stream = new DigestInputStream(stream, SHA256);
    byte[] buff = new byte[HASH_LENGTH];
    // Read up to the 64K in on read
    SHA256Stream.read(buff, 0, HASH_LENGTH);
    // Return the new instance from the calulated details
    return Hex.encodeHexString(SHA256.digest());
}

From source file:org.slc.sli.test.utils.DataUtils.java

public static final String createMd5ForFile(String file) {
    File myFile = new File(file);
    DigestInputStream dis = null;
    try {// www  . j  a v a  2s .c  o m
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.reset();
        dis = new DigestInputStream(new FileInputStream(myFile), md);
        byte[] buf = new byte[1024];
        while (dis.read(buf, 0, 1024) != -1) {
        }
        return Hex.encodeHexString(dis.getMessageDigest().digest());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.jpeterson.util.etag.FileETag.java

/**
 * Calculates the ETag for a file based on file metadata. The file metadata
 * used in the ETag calculation is set via <code>setFlags(int)</code>.
 * /*from   www . jav  a  2 s .com*/
 * @param o
 *            The <code>File</code> to calculate the ETag for.
 * @return The ETag value. May be <code>null</code> if an ETag can not be
 *         calculated.
 * @see #setFlags(int)
 */
public String calculate(Object o) {
    StringBuffer buffer = new StringBuffer();
    MessageDigest messageDigest;
    byte[] digest;
    File file;

    try {
        file = (File) o;
    } catch (ClassCastException e) {
        System.err.println("Unable to cast the object to a File: " + o);
        return null;
    }

    if (!file.exists()) {
        System.err.println("Unable to calculate ETag; file doesn't exist: " + file);
        return null;
    }

    try {
        messageDigest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }

    // order of the flags is important! changing the order will change the
    // ETag value

    if ((flags & FLAG_CONTENT) != 0) {
        try {
            DigestInputStream digestInputStream = new DigestInputStream(new FileInputStream(file),
                    messageDigest);
            byte[] b = new byte[1024];

            while (digestInputStream.read(b, 0, b.length) > 0) {
                // adding content to the MessageDigest
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    if ((flags & FLAG_MTIME) != 0) {
        buffer.append(file.lastModified());
    }

    if ((flags & FLAG_SIZE) != 0) {
        buffer.append(file.length());
    }

    digest = messageDigest.digest(buffer.toString().getBytes());

    return new String(Hex.encodeHex(digest));
}

From source file:org.apache.jackrabbit.oak.spi.blob.FileBlobStore.java

@Override
public String writeBlob(String tempFilePath) throws IOException {
    File file = new File(tempFilePath);
    InputStream in = new FileInputStream(file);
    MessageDigest messageDigest;/*from  w w w  .j av a  2s.c o m*/
    try {
        messageDigest = MessageDigest.getInstance(HASH_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }
    DigestInputStream din = new DigestInputStream(in, messageDigest);
    long length = file.length();
    try {
        while (true) {
            int len = din.read(buffer, 0, buffer.length);
            if (len < 0) {
                break;
            }
        }
    } finally {
        din.close();
    }
    ByteArrayOutputStream idStream = new ByteArrayOutputStream();
    idStream.write(TYPE_HASH);
    IOUtils.writeVarInt(idStream, 0);
    IOUtils.writeVarLong(idStream, length);
    byte[] digest = messageDigest.digest();
    File f = getFile(digest, false);
    if (f.exists()) {
        file.delete();
    } else {
        File parent = f.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        file.renameTo(f);
    }
    IOUtils.writeVarInt(idStream, digest.length);
    idStream.write(digest);
    byte[] id = idStream.toByteArray();
    String blobId = StringUtils.convertBytesToHex(id);
    usesBlobId(blobId);
    return blobId;
}

From source file:stargate.drivers.recipe.sha1fixed.SHA1FixedChunkRecipeGeneratorDriver.java

@Override
public synchronized Recipe getRecipe(DataObjectMetadata metadata, InputStream is) throws IOException {
    if (metadata == null || metadata.isEmpty()) {
        throw new IllegalArgumentException("metadata is null or empty");
    }//from  w  w  w.j av  a  2s.com

    if (is == null) {
        throw new IllegalArgumentException("is is null");
    }

    List<RecipeChunk> chunk = new ArrayList<RecipeChunk>();

    int bufferSize = Math.min(this.chunkSize, BUFFER_SIZE);
    byte[] buffer = new byte[bufferSize];

    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        DigestInputStream dis = new DigestInputStream(is, messageDigest);

        long chunkOffset = 0;

        while (chunkOffset < metadata.getObjectSize()) {
            int chunkLength = 0;
            int nread = 0;
            int toread = this.chunkSize;

            while ((nread = dis.read(buffer, 0, Math.min(toread, bufferSize))) > 0) {
                chunkLength += nread;
                toread -= nread;
                if (toread == 0) {
                    break;
                }
            }

            byte[] digest = messageDigest.digest();
            chunk.add(new RecipeChunk(chunkOffset, chunkLength, digest));
            messageDigest.reset();

            if (nread <= 0) {
                //EOF
                break;
            }

            chunkOffset += chunkLength;
        }

        dis.close();
    } catch (NoSuchAlgorithmException ex) {
        throw new IOException(ex);
    }

    return new Recipe(metadata, HASH_ALGORITHM, this.chunkSize, chunk);
}

From source file:org.dspace.services.impl.storage.DSpaceStorageService.java

@Override
public Bitstream register(int assetstore, String path) throws StorageException {
    this.init();/*from ww w  . jav a2s .  c o m*/

    // mark this bitstream as a registered bitstream
    String sInternalId = Bitstream.REGISTERED_FLAG + path;

    // Create a deleted bitstream row, using a separate DB connection
    Bitstream bitstream = new Bitstream();
    bitstream.setDeleted(true);
    bitstream.setInternalId(sInternalId);
    bitstream.setStoreNumber(assetstore);

    bitstreamDao.save(bitstream);

    // get a reference to the file
    GeneralFile file = getFile(bitstream);

    // read through a DigestInputStream that will work out the MD5
    //
    // DSpace refers to checksum, writes it in METS, and uses it as an
    // AIP filename (!), but never seems to validate with it. Furthermore,
    // DSpace appears to hardcode the algorithm to MD5 in some places--see
    // METSExport.java.
    //
    // To remain compatible with DSpace we calculate an MD5 checksum on
    // LOCAL registered files. But for REMOTE (e.g. SRB) files we
    // calculate an MD5 on just the fileNAME. The reasoning is that in the
    // case of a remote file, calculating an MD5 on the file itself will
    // generate network traffic to read the file's bytes. In this case it
    // would be better have a proxy process calculate MD5 and store it as
    // an SRB metadata attribute so it can be retrieved simply from SRB.
    //
    // TODO set this up as a proxy server process so no net activity

    // FIXME this is a first class HACK! for the reasons described above
    if (file instanceof LocalFile) {

        // get MD5 on the file for local file
        DigestInputStream dis = null;
        try {
            dis = new DigestInputStream(FileFactory.newFileInputStream(file), MessageDigest.getInstance("MD5"));
        } catch (NoSuchAlgorithmException e) {
            log.warn("Caught NoSuchAlgorithmException", e);
            throw new StorageException("Invalid checksum algorithm", e);
        } catch (IOException e) {
            log.error("File: " + file.getAbsolutePath() + " to be registered cannot be opened - is it "
                    + "really there?");
            throw new StorageException(e);
        }
        final int BUFFER_SIZE = 1024 * 4;
        final byte[] buffer = new byte[BUFFER_SIZE];
        try {
            while (true) {
                final int count = dis.read(buffer, 0, BUFFER_SIZE);
                if (count == -1) {
                    break;
                }
            }
            bitstream.setChecksum(Utils.toHex(dis.getMessageDigest().digest()));
            dis.close();
        } catch (IOException e) {
            throw new StorageException(e);
        }
    } else if (file instanceof SRBFile) {
        if (!file.exists()) {
            log.error("File: " + file.getAbsolutePath() + " is not in SRB MCAT");
            throw new StorageException("File is not in SRB MCAT");
        }

        // get MD5 on just the filename (!) for SRB file
        int iLastSlash = path.lastIndexOf('/');
        String sFilename = path.substring(iLastSlash + 1);
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            log.error("Caught NoSuchAlgorithmException", e);
            throw new StorageException("Invalid checksum algorithm", e);
        }
        bitstream.setChecksum(Utils.toHex(md.digest(sFilename.getBytes())));
    } else {
        throw new StorageException("Unrecognized file type - " + "not local, not SRB");
    }

    bitstream.setChecksumAlgorithm("MD5");
    bitstream.setSize(file.length());
    bitstream.setDeleted(false);

    bitstreamDao.save(bitstream);

    if (log.isDebugEnabled()) {
        log.debug("Stored bitstream " + bitstream.getID() + " in file " + file.getAbsolutePath());
    }
    return bitstream;
}