Search in sources :

Example 36 with DigestInputStream

use of java.security.DigestInputStream in project bnd by bndtools.

the class LocalIndexedRepo method put.

/* NOTE: this is a straight copy of FileRepo.put */
@Override
public synchronized PutResult put(InputStream stream, PutOptions options) throws Exception {
    /* determine if the put is allowed */
    if (readOnly) {
        throw new IOException("Repository is read-only");
    }
    if (options == null)
        options = DEFAULTOPTIONS;
    /* both parameters are required */
    if (stream == null)
        throw new IllegalArgumentException("No stream and/or options specified");
    /* the root directory of the repository has to be a directory */
    if (!storageDir.isDirectory()) {
        throw new IOException("Repository directory " + storageDir + " is not a directory");
    }
    /*
		 * setup a new stream that encapsulates the stream and calculates (when
		 * needed) the digest
		 */
    DigestInputStream dis = new DigestInputStream(stream, MessageDigest.getInstance("SHA-1"));
    File tmpFile = null;
    try {
        /*
			 * copy the artifact from the (new/digest) stream into a temporary
			 * file in the root directory of the repository
			 */
        tmpFile = IO.createTempFile(storageDir, "put", ".bnd");
        IO.copy(dis, tmpFile);
        /* beforeGet the digest if available */
        byte[] disDigest = dis.getMessageDigest().digest();
        if (options.digest != null && !Arrays.equals(options.digest, disDigest))
            throw new IOException("Retrieved artifact digest doesn't match specified digest");
        /* put the artifact into the repository (from the temporary file) */
        File file = putArtifact(tmpFile);
        PutResult result = new PutResult();
        if (file != null) {
            result.digest = disDigest;
            result.artifact = file.toURI();
        }
        return result;
    } finally {
        if (tmpFile != null && tmpFile.exists()) {
            IO.delete(tmpFile);
        }
    }
}
Also used : DigestInputStream(java.security.DigestInputStream) IOException(java.io.IOException) File(java.io.File)

Example 37 with DigestInputStream

use of java.security.DigestInputStream in project bnd by bndtools.

the class FileRepo method put.

/*
	 * (non-Javadoc)
	 * @see aQute.bnd.service.RepositoryPlugin#put(java.io.InputStream,
	 * aQute.bnd.service.RepositoryPlugin.PutOptions)
	 */
public PutResult put(InputStream stream, PutOptions options) throws Exception {
    /* determine if the put is allowed */
    if (!canWrite) {
        throw new IOException("Repository is read-only");
    }
    assert stream != null;
    if (options == null)
        options = DEFAULTOPTIONS;
    init();
    /*
		 * copy the artifact from the (new/digest) stream into a temporary file
		 * in the root directory of the repository
		 */
    File tmpFile = IO.createTempFile(root, "put", ".jar");
    try (DigestInputStream dis = new DigestInputStream(stream, MessageDigest.getInstance("SHA-1"))) {
        IO.copy(dis, tmpFile);
        byte[] digest = dis.getMessageDigest().digest();
        if (options.digest != null && !Arrays.equals(digest, options.digest))
            throw new IOException("Retrieved artifact digest doesn't match specified digest");
        /*
				 * put the artifact into the repository (from the temporary
				 * file)
				 */
        beforePut(tmpFile);
        File file = putArtifact(tmpFile, options, digest);
        PutResult result = new PutResult();
        result.digest = digest;
        result.artifact = file.toURI();
        return result;
    } catch (Exception e) {
        abortPut(tmpFile);
        throw e;
    } finally {
        IO.delete(tmpFile);
    }
}
Also used : DigestInputStream(java.security.DigestInputStream) IOException(java.io.IOException) File(java.io.File) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 38 with DigestInputStream

use of java.security.DigestInputStream in project bnd by bndtools.

the class CAFS method write.

/**
	 * Store an input stream in the CAFS while calculating and returning the
	 * SHA-1 code.
	 * 
	 * @param in The input stream to store.
	 * @return The SHA-1 code.
	 * @throws Exception if anything goes wrong
	 */
public SHA1 write(InputStream in) throws Exception {
    Deflater deflater = new Deflater();
    MessageDigest md = MessageDigest.getInstance(ALGORITHM);
    DigestInputStream din = new DigestInputStream(in, md);
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DeflaterOutputStream dout = new DeflaterOutputStream(bout, deflater);
    copy(din, dout);
    synchronized (store) {
        // First check if it already exists
        SHA1 sha1 = new SHA1(md.digest());
        long search = index.search(sha1.digest());
        if (search > 0)
            return sha1;
        byte[] compressed = bout.toByteArray();
        // we need to append this file to our store,
        // which requires a lock. However, we are in a race
        // so others can get the lock between us getting
        // the length and someone else getting the lock.
        // So we must verify after we get the lock that the
        // length was unchanged.
        FileLock lock = null;
        try {
            long insertPoint;
            int recordLength = compressed.length + HEADERLENGTH;
            while (true) {
                insertPoint = store.length();
                lock = channel.lock(insertPoint, recordLength, false);
                if (store.length() == insertPoint)
                    break;
                // We got the wrong lock, someone else
                // got in between reading the length
                // and locking
                lock.release();
            }
            int totalLength = deflater.getTotalIn();
            store.seek(insertPoint);
            update(sha1.digest(), compressed, totalLength);
            index.insert(sha1.digest(), insertPoint);
            return sha1;
        } finally {
            if (lock != null)
                lock.release();
        }
    }
}
Also used : SHA1(aQute.libg.cryptography.SHA1) Deflater(java.util.zip.Deflater) DigestInputStream(java.security.DigestInputStream) DeflaterOutputStream(java.util.zip.DeflaterOutputStream) FileLock(java.nio.channels.FileLock) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MessageDigest(java.security.MessageDigest)

Example 39 with DigestInputStream

use of java.security.DigestInputStream in project weiui by kuaifan.

the class FileUtils method getFileMD5.

/**
 * Return the MD5 of file.
 *
 * @param file The file.
 * @return the md5 of file
 */
public static byte[] getFileMD5(final File file) {
    if (file == null)
        return null;
    DigestInputStream dis = null;
    try {
        FileInputStream fis = new FileInputStream(file);
        MessageDigest md = MessageDigest.getInstance("MD5");
        dis = new DigestInputStream(fis, md);
        byte[] buffer = new byte[1024 * 256];
        while (true) {
            if (!(dis.read(buffer) > 0))
                break;
        }
        md = dis.getMessageDigest();
        return md.digest();
    } catch (NoSuchAlgorithmException | IOException e) {
        e.printStackTrace();
    } finally {
        CloseUtils.closeIO(dis);
    }
    return null;
}
Also used : DigestInputStream(java.security.DigestInputStream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) MessageDigest(java.security.MessageDigest) FileInputStream(java.io.FileInputStream)

Example 40 with DigestInputStream

use of java.security.DigestInputStream in project smarthome by eclipse.

the class Firmware method getBytes.

/**
 * Returns the binary content of the firmware using the firmware´s input stream. If the firmware provides a MD5 hash
 * value then this operation will also validate the MD5 checksum of the firmware.
 *
 * @return the binary content of the firmware (can be null)
 * @throws IllegalStateException if the MD5 hash value of the firmware is invalid
 */
public synchronized byte[] getBytes() {
    if (inputStream == null) {
        return null;
    }
    if (bytes == null) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            try (DigestInputStream dis = new DigestInputStream(inputStream, md)) {
                bytes = IOUtils.toByteArray(dis);
            } catch (IOException ioEx) {
                LOGGER.error("Cannot read firmware with UID {}.", uid, ioEx);
                return null;
            }
            byte[] digest = md.digest();
            if (md5Hash != null && digest != null) {
                StringBuilder digestString = new StringBuilder();
                for (byte b : digest) {
                    digestString.append(String.format("%02x", b));
                }
                if (!md5Hash.equals(digestString.toString())) {
                    bytes = null;
                    throw new IllegalStateException(String.format("Invalid MD5 checksum. Expected %s, but was %s.", md5Hash, digestString));
                }
            }
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("Cannot calculate MD5 checksum.", e);
            bytes = null;
            return null;
        }
    }
    return bytes;
}
Also used : DigestInputStream(java.security.DigestInputStream) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

Aggregations

DigestInputStream (java.security.DigestInputStream)161 MessageDigest (java.security.MessageDigest)124 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)78 IOException (java.io.IOException)62 InputStream (java.io.InputStream)53 ByteArrayInputStream (java.io.ByteArrayInputStream)38 FileInputStream (java.io.FileInputStream)34 File (java.io.File)19 BufferedInputStream (java.io.BufferedInputStream)13 ByteArrayOutputStream (java.io.ByteArrayOutputStream)9 FileOutputStream (java.io.FileOutputStream)8 URL (java.net.URL)7 OutputStream (java.io.OutputStream)6 BigInteger (java.math.BigInteger)5 DigestOutputStream (java.security.DigestOutputStream)5 HashMap (java.util.HashMap)5 FileNotFoundException (java.io.FileNotFoundException)4 Formatter (java.util.Formatter)4 ByteUtil (com.zimbra.common.util.ByteUtil)3 Path (java.nio.file.Path)3