List of usage examples for java.security DigestInputStream DigestInputStream
public DigestInputStream(InputStream stream, MessageDigest digest)
From source file:org.digitalcampus.oppia.task.DownloadMediaTask.java
@Override protected Payload doInBackground(Payload... params) { Payload payload = params[0];//from w w w .j a v a 2s . com for (Object o : payload.getData()) { Media m = (Media) o; File file = new File(MobileLearning.MEDIA_PATH, m.getFilename()); try { URL u = new URL(m.getDownloadUrl()); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); c.setConnectTimeout( Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection), ctx.getString(R.string.prefServerTimeoutConnection)))); c.setReadTimeout( Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response), ctx.getString(R.string.prefServerTimeoutResponse)))); int fileLength = c.getContentLength(); DownloadProgress dp = new DownloadProgress(); dp.setMessage(m.getFilename()); dp.setProgress(0); publishProgress(dp); FileOutputStream f = new FileOutputStream(file); InputStream in = c.getInputStream(); MessageDigest md = MessageDigest.getInstance("MD5"); in = new DigestInputStream(in, md); byte[] buffer = new byte[8192]; int len1 = 0; long total = 0; int progress = 0; while ((len1 = in.read(buffer)) > 0) { total += len1; progress = (int) (total * 100) / fileLength; if (progress > 0) { dp.setProgress(progress); publishProgress(dp); } f.write(buffer, 0, len1); } f.close(); dp.setProgress(100); publishProgress(dp); // check the file digest matches, otherwise delete the file // (it's either been a corrupted download or it's the wrong file) byte[] digest = md.digest(); String resultMD5 = ""; for (int i = 0; i < digest.length; i++) { resultMD5 += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1); } Log.d(TAG, "supplied digest: " + m.getDigest()); Log.d(TAG, "calculated digest: " + resultMD5); if (!resultMD5.contains(m.getDigest())) { this.deleteFile(file); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } else { payload.setResult(true); payload.setResultResponse(ctx.getString(R.string.success_media_download, m.getFilename())); } } catch (ClientProtocolException e1) { e1.printStackTrace(); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } catch (IOException e1) { e1.printStackTrace(); this.deleteFile(file); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } catch (NoSuchAlgorithmException e) { if (!MobileLearning.DEVELOPER_MODE) { BugSenseHandler.sendException(e); } else { e.printStackTrace(); } payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } } return payload; }
From source file:org.duracloud.chunk.ChunkableContentTest.java
private void verifyTotalChunkChecksum() throws Exception { MessageDigest md5 = MessageDigest.getInstance(Algorithm.MD5.name()); DigestInputStream istream;/*from w w w .j a v a 2 s . c o m*/ for (File chunk : chunkFiles) { istream = new DigestInputStream(new FileInputStream(chunk), md5); read(istream); md5 = istream.getMessageDigest(); IOUtils.closeQuietly(istream); } Assert.assertNotNull(md5); Assert.assertTrue(MessageDigest.isEqual(contentChecksum.digest(), md5.digest())); }
From source file:org.rhq.gui.content.YumMetadata.java
protected static String getSHA(StringBuffer primaryXML) throws NoSuchAlgorithmException, IOException { // Note: For RHEL6 this may need to change to "SHA-256", // going for SHA for now, as it's a lowest common denominator so it can work with older clients. MessageDigest md = MessageDigest.getInstance("SHA"); ByteArrayInputStream bis = new ByteArrayInputStream(primaryXML.toString().getBytes()); DigestInputStream mdistr = new DigestInputStream(bis, md); while (mdistr.read() != -1) { ;/*from w w w . j a v a 2s . c o m*/ } mdistr.close(); return Hex.encodeHexString(md.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 {// w w w. j a v a2 s . 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:org.duracloud.common.util.ChecksumUtil.java
/** * Wraps an InputStream with a DigestInputStream in order to compute * a checksum as the stream is being read. * * @param inStream The stream to wrap/* w w w .j ava 2 s.c o m*/ * @param algorithm The algorithm used to compute the digest * @return The original stream wrapped as a DigestInputStream */ public static DigestInputStream wrapStream(InputStream inStream, Algorithm algorithm) { MessageDigest streamDigest = null; try { streamDigest = MessageDigest.getInstance(algorithm.toString()); } catch (NoSuchAlgorithmException e) { String error = "Could not create a MessageDigest because the " + "required algorithm " + algorithm.toString() + " is not supported."; throw new RuntimeException(error); } DigestInputStream wrappedContent = new DigestInputStream(inStream, streamDigest); return wrappedContent; }
From source file:org.wso2.carbon.connector.amazons3.auth.AmazonS3ContentMD5Builder.java
/** * Consume the string type delete configuration and returns its Base-64 encoded MD5 checksum as a string. * * @param deleteConfig gets delete configuration as a string. * @return String type base-64 encoded MD5 checksum. * @throws IOException if an I/O error occurs when reading bytes of data from input stream. * @throws NoSuchAlgorithmException if no implementation for the specified algorithm. *//*w w w . j av a 2 s .co m*/ private String getContentMD5Header(final String deleteConfig) throws IOException, NoSuchAlgorithmException { String contentHeader = null; // convert String into InputStream final InputStream inputStream = new ByteArrayInputStream(deleteConfig.getBytes(Charset.defaultCharset())); final DigestInputStream digestInputStream = new DigestInputStream(inputStream, MessageDigest.getInstance(AmazonS3Constants.MD5)); final byte[] buffer = new byte[AmazonS3Constants.BUFFER_SIZE]; while (digestInputStream.read(buffer) > 0) { contentHeader = new String(Base64.encodeBase64(digestInputStream.getMessageDigest().digest()), Charset.defaultCharset()); } return contentHeader; }
From source file:org.roda.core.util.FileUtility.java
public static Map<String, String> copyAndChecksums(InputStream in, OutputStream out, Collection<String> algorithms) throws NoSuchAlgorithmException, IOException { Map<String, String> ret = new HashMap<>(); Map<String, DigestInputStream> streams = new HashMap<>(); InputStream stream = in;/*from www . j a v a 2 s. co m*/ for (String algorithm : algorithms) { stream = new DigestInputStream(stream, MessageDigest.getInstance(algorithm)); streams.put(algorithm, (DigestInputStream) stream); } IOUtils.copyLarge(stream, out); for (Entry<String, DigestInputStream> entry : streams.entrySet()) { ret.put(entry.getKey(), byteArrayToHexString(entry.getValue().getMessageDigest().digest())); } return ret; }
From source file:org.apache.hadoop.hdfs.util.MD5FileUtils.java
/** * Read dataFile and compute its MD5 checksum. *///from w w w .j a v a2 s .c o m public static MD5Hash computeMd5ForFile(File dataFile) throws IOException { InputStream in = new FileInputStream(dataFile); try { MessageDigest digester = MD5Hash.getDigester(); DigestInputStream dis = new DigestInputStream(in, digester); IOUtils.copyBytes(dis, new IOUtils.NullOutputStream(), 128 * 1024); return new MD5Hash(digester.digest()); } finally { IOUtils.closeStream(in); } }
From source file:org.carlspring.strongbox.storage.metadata.nuget.TempNupkgFile.java
/** * Creates a temporary file based on the stream. * * @param inputStream/* w ww. ja v a 2s. c om*/ * data stream * @param targetFile * file to copy the package to * @return data file * @throws IOException * read / write error * @throws NoSuchAlgorithmException * the system does not have an algorithm for calculating the * value of HASH */ private static String copyDataAndCalculateHash(InputStream inputStream, File targetFile) throws IOException, NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance(MessageDigestAlgorithms.SHA_512); DigestInputStream digestInputStream = new DigestInputStream(inputStream, messageDigest); try (FileOutputStream fileOutputStream = new FileOutputStream(targetFile); ReadableByteChannel src = Channels.newChannel(digestInputStream); FileChannel dest = fileOutputStream.getChannel();) { fastChannelCopy(src, dest); byte[] digest = digestInputStream.getMessageDigest().digest(); return DatatypeConverter.printBase64Binary(digest); } }
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>. * // www. ja v a 2 s .co m * @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)); }