List of usage examples for java.security DigestInputStream DigestInputStream
public DigestInputStream(InputStream stream, MessageDigest digest)
From source file:de.burlov.amazon.s3.dirsync.DirSync.java
private byte[] digestFile(File file, MessageDigest digest) throws IOException { DigestInputStream in = new DigestInputStream(new FileInputStream(file), digest); IOUtils.copy(in, new NullOutputStream()); in.close();/*from w w w . ja v a2 s .c o m*/ return in.getMessageDigest().digest(); }
From source file:com.example.download.DownloadThread.java
/** * Prepare the destination file to receive data. If the file already exists, we'll set up * appropriately for resumption.//from w ww . j a va2s. c om */ private void setupDestinationFile(State state, InnerState innerState) throws StopRequest { if (!TextUtils.isEmpty(state.mFilename)) { // only true if we've already run a thread for this download if (!Helper.isFilenameValid(state.mFilename, state.mSourceType)) { // this should never happen throw new StopRequest(DownloadManager.Impl.STATUS_FILE_ERROR, "found invalid internal destination filename"); } // We're resuming a download that got interrupted File f = new File(state.mFilename); if (f.exists()) { long fileLength = f.length(); if (fileLength == 0) { // The download hadn't actually started, we can restart from scratch f.delete(); state.mFilename = null; } else if (mInfo.mETag == null) { // This should've been caught upon failure f.delete(); throw new StopRequest(DownloadManager.Impl.STATUS_CANNOT_RESUME, "Trying to resume a download that can't be resumed"); } else { // All right, we'll be able to resume this download try { state.mStream = new FileOutputStream(state.mFilename, true); FileInputStream fis = new FileInputStream(state.mFilename); DigestInputStream dis = new DigestInputStream(fis, state.mDigester); byte[] buffer = new byte[8192]; while (dis.read(buffer) != -1) { // read the digest } dis.close(); fis.close(); } catch (FileNotFoundException exc) { throw new StopRequest(DownloadManager.Impl.STATUS_FILE_ERROR, "while opening destination for resuming: " + exc.toString(), exc); } catch (IOException e) { throw new StopRequest(DownloadManager.Impl.STATUS_FILE_ERROR, "while opening destination for resuming: " + e.toString(), e); } innerState.mBytesSoFar = (int) fileLength; if (mInfo.mTotalBytes != -1) { innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes); } innerState.mHeaderETag = mInfo.mETag; innerState.mContinuingDownload = true; } } } if (state.mStream != null && mInfo.mDestination == DownloadManager.Impl.DESTINATION_EXTERNAL) { closeDestination(state); } }
From source file:org.zanata.action.VersionHomeAction.java
private void uploadAdapterFile(DocumentType docType) { String fileName = sourceFileUpload.getFileName(); String docId = sourceFileUpload.getDocId(); String documentPath = ""; if (docId == null) { documentPath = sourceFileUpload.getDocumentPath(); } else if (docId.contains("/")) { documentPath = docId.substring(0, docId.lastIndexOf('/')); }// w w w. j a v a2s . c om File tempFile = null; byte[] md5hash; try { MessageDigest md = MessageDigest.getInstance("MD5"); InputStream fileContents = new DigestInputStream(sourceFileUpload.getFileContents(), md); tempFile = translationFileServiceImpl.persistToTempFile(fileContents); md5hash = md.digest(); } catch (ZanataServiceException e) { VersionHomeAction.log.error("Failed writing temp file for document {}", e, sourceFileUpload.getDocId()); setMessage(FacesMessage.SEVERITY_ERROR, "Error saving uploaded document " + fileName + " to server."); return; } catch (NoSuchAlgorithmException e) { VersionHomeAction.log.error("MD5 hash algorithm not available", e); setMessage(FacesMessage.SEVERITY_ERROR, "Error generating hash for uploaded document " + fileName + "."); return; } HDocument document = null; try { Resource doc; if (docId == null) { doc = translationFileServiceImpl.parseAdapterDocumentFile(tempFile.toURI(), documentPath, fileName, getOptionalParams(), Optional.of(docType.name())); } else { doc = translationFileServiceImpl.parseUpdatedAdapterDocumentFile(tempFile.toURI(), docId, fileName, getOptionalParams(), Optional.of(docType.name())); } doc.setLang(new LocaleId(sourceFileUpload.getSourceLang())); Set<String> extensions = Collections.<String>emptySet(); // TODO Copy Trans values document = documentServiceImpl.saveDocument(projectSlug, versionSlug, doc, extensions, false); showUploadSuccessMessage(); } catch (SecurityException e) { setMessage(FacesMessage.SEVERITY_ERROR, "Error reading uploaded document " + fileName + " on server."); } catch (ZanataServiceException e) { setMessage(FacesMessage.SEVERITY_ERROR, "Invalid document format for " + fileName); } if (document == null) { // error message for failed parse already added. } else { HRawDocument rawDocument = new HRawDocument(); rawDocument.setDocument(document); rawDocument.setContentHash(new String(PasswordUtil.encodeHex(md5hash))); rawDocument.setType(docType); rawDocument.setUploadedBy(identity.getCredentials().getUsername()); Optional<String> params = getOptionalParams(); if (params.isPresent()) { rawDocument.setAdapterParameters(params.get()); } try { String name = projectSlug + ":" + versionSlug + ":" + docId; virusScanner.scan(tempFile, name); } catch (VirusDetectedException e) { VersionHomeAction.log.warn("File failed virus scan: {}", e.getMessage()); setMessage(FacesMessage.SEVERITY_ERROR, "uploaded file did not pass virus scan"); } filePersistService.persistRawDocumentContentFromFile(rawDocument, tempFile, FilenameUtils.getExtension(fileName)); documentDAO.addRawDocument(document, rawDocument); documentDAO.flush(); } translationFileServiceImpl.removeTempFile(tempFile); }
From source file:ch.cyberduck.core.s3.S3Path.java
private Future<MultipartPart> submitPart(final BandwidthThrottle throttle, final StreamListener listener, final TransferStatus status, final MultipartUpload multipart, final ExecutorService pool, final int partNumber, final long offset, final long length) throws ConnectionCanceledException { if (pool.isShutdown()) { throw new ConnectionCanceledException(); }//from w ww . j ava 2 s . c o m log.info(String.format("Submit part %d to queue", partNumber)); return pool.submit(new Callable<MultipartPart>() { @Override public MultipartPart call() throws IOException, ServiceException { final Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put("uploadId", multipart.getUploadId()); requestParameters.put("partNumber", String.valueOf(partNumber)); InputStream in = null; ResponseOutputStream<StorageObject> out = null; MessageDigest digest = null; try { if (!Preferences.instance().getBoolean("s3.upload.metadata.md5")) { // Content-MD5 not set. Need to verify ourselves instad of S3 try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error(e.getMessage()); } } if (null == digest) { log.warn("MD5 calculation disabled"); in = getLocal().getInputStream(); } else { in = new DigestInputStream(getLocal().getInputStream(), digest); } out = write(new StorageObject(getKey()), length, requestParameters); upload(out, in, throttle, listener, offset, length, status); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } final StorageObject part = out.getResponse(); if (null != digest) { // Obtain locally-calculated MD5 hash String hexMD5 = ServiceUtils.toHex(digest.digest()); getSession().getClient().verifyExpectedAndActualETagValues(hexMD5, part); } // Populate part with response data that is accessible via the object's metadata return new MultipartPart(partNumber, part.getLastModifiedDate(), part.getETag(), part.getContentLength()); } }); }
From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java
/** * @param algorithm/*w w w . j a va 2 s.c o m*/ * @param fileName * @return * @throws Exception */ private String calculateHash(final File file) throws Exception { if (sha1 != null) { FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); DigestInputStream dis = new DigestInputStream(bis, sha1); // read the file and update the hash calculation while (dis.read() != -1) ; // get the hash value as byte array byte[] hash = sha1.digest(); dis.close(); return byteArray2Hex(hash); } return null; }
From source file:com.mobicage.rogerthat.plugins.messaging.BrandingMgr.java
private BrandingResult extractBranding(final BrandedItem item, final File encryptedBrandingFile, final File tmpDecryptedBrandingFile, final File tmpBrandingDir) throws BrandingFailureException { try {/*from w ww . j a v a 2s . co m*/ L.i("Extracting " + tmpDecryptedBrandingFile + " (" + item.brandingKey + ")"); File brandingFile = new File(tmpBrandingDir, "branding.html"); File watermarkFile = null; Integer backgroundColor = null; Integer menuItemColor = null; ColorScheme scheme = ColorScheme.light; boolean showHeader = true; String contentType = null; boolean wakelockEnabled = false; ByteArrayOutputStream brandingBos = new ByteArrayOutputStream(); try { MessageDigest digester = MessageDigest.getInstance("SHA256"); DigestInputStream dis = new DigestInputStream( new BufferedInputStream(new FileInputStream(tmpDecryptedBrandingFile)), digester); try { ZipInputStream zis = new ZipInputStream(dis); try { byte data[] = new byte[BUFFER_SIZE]; ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { L.d("Extracting: " + entry); int count = 0; if (entry.getName().equals("branding.html")) { while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) { brandingBos.write(data, 0, count); } } else { if (entry.isDirectory()) { L.d("Skipping branding dir " + entry.getName()); continue; } File destination = new File(tmpBrandingDir, entry.getName()); destination.getParentFile().mkdirs(); if ("__watermark__".equals(entry.getName())) { watermarkFile = destination; } final OutputStream fos = new BufferedOutputStream(new FileOutputStream(destination), BUFFER_SIZE); try { while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) { fos.write(data, 0, count); } } finally { fos.close(); } } } while (dis.read(data) >= 0) ; } finally { zis.close(); } } finally { dis.close(); } String hexDigest = com.mobicage.rogerthat.util.TextUtils.toHex(digester.digest()); if (!hexDigest.equals(item.brandingKey)) { encryptedBrandingFile.delete(); SystemUtils.deleteDir(tmpBrandingDir); throw new BrandingFailureException("Branding cache was invalid!"); } brandingBos.flush(); byte[] brandingBytes = brandingBos.toByteArray(); if (brandingBytes.length == 0) { encryptedBrandingFile.delete(); SystemUtils.deleteDir(tmpBrandingDir); throw new BrandingFailureException("Invalid branding package!"); } String brandingHtml = new String(brandingBytes, "UTF8"); switch (item.type) { case BrandedItem.TYPE_MESSAGE: MessageTO message = (MessageTO) item.object; brandingHtml = brandingHtml.replace(NUNTIUZ_MESSAGE, TextUtils.htmlEncode(message.message).replace("\r", "").replace("\n", "<br>")); brandingHtml = brandingHtml.replace(NUNTIUZ_TIMESTAMP, TimeUtils.getDayTimeStr(mContext, message.timestamp * 1000)); FriendsPlugin friendsPlugin = mMainService.getPlugin(FriendsPlugin.class); brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME, TextUtils.htmlEncode(friendsPlugin.getName(message.sender))); break; case BrandedItem.TYPE_FRIEND: FriendTO friend = (FriendTO) item.object; // In this case Friend is fully populated brandingHtml = brandingHtml.replace(NUNTIUZ_MESSAGE, TextUtils.htmlEncode(friend.description).replace("\r", "").replace("\n", "<br>")); brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME, TextUtils.htmlEncode(friend.name)); break; case BrandedItem.TYPE_GENERIC: if (item.object instanceof FriendTO) { brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME, TextUtils.htmlEncode(((FriendTO) item.object).name)); } break; } Matcher matcher = RegexPatterns.BRANDING_BACKGROUND_COLOR.matcher(brandingHtml); if (matcher.find()) { String bg = matcher.group(1); if (bg.length() == 4) { StringBuilder sb = new StringBuilder(); sb.append("#"); sb.append(bg.charAt(1)); sb.append(bg.charAt(1)); sb.append(bg.charAt(2)); sb.append(bg.charAt(2)); sb.append(bg.charAt(3)); sb.append(bg.charAt(3)); bg = sb.toString(); } backgroundColor = Color.parseColor(bg); } matcher = RegexPatterns.BRANDING_MENU_ITEM_COLOR.matcher(brandingHtml); if (matcher.find()) { String bg = matcher.group(1); if (bg.length() == 4) { StringBuilder sb = new StringBuilder(); sb.append("#"); sb.append(bg.charAt(1)); sb.append(bg.charAt(1)); sb.append(bg.charAt(2)); sb.append(bg.charAt(2)); sb.append(bg.charAt(3)); sb.append(bg.charAt(3)); bg = sb.toString(); } menuItemColor = Color.parseColor(bg); } matcher = RegexPatterns.BRANDING_COLOR_SCHEME.matcher(brandingHtml); if (matcher.find()) { String schemeStr = matcher.group(1); scheme = "dark".equalsIgnoreCase(schemeStr) ? ColorScheme.dark : ColorScheme.light; } matcher = RegexPatterns.BRANDING_SHOW_HEADER.matcher(brandingHtml); if (matcher.find()) { String showHeaderStr = matcher.group(1); showHeader = "true".equalsIgnoreCase(showHeaderStr); } matcher = RegexPatterns.BRANDING_CONTENT_TYPE.matcher(brandingHtml); if (matcher.find()) { String contentTypeStr = matcher.group(1); L.i("Branding content-type: " + contentTypeStr); if (AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(contentTypeStr)) { File tmpBrandingFile = new File(tmpBrandingDir, "embed.pdf"); if (tmpBrandingFile.exists()) { contentType = AttachmentViewerActivity.CONTENT_TYPE_PDF; } } } Dimension dimension1 = null; Dimension dimension2 = null; matcher = RegexPatterns.BRANDING_DIMENSIONS.matcher(brandingHtml); if (matcher.find()) { String dimensionsStr = matcher.group(1); L.i("Branding dimensions: " + dimensionsStr); String[] dimensions = dimensionsStr.split(","); try { dimension1 = new Dimension(Integer.parseInt(dimensions[0]), Integer.parseInt(dimensions[1])); dimension2 = new Dimension(Integer.parseInt(dimensions[2]), Integer.parseInt(dimensions[3])); } catch (Exception e) { L.bug("Invalid branding dimension: " + matcher.group(), e); } } matcher = RegexPatterns.BRANDING_WAKELOCK_ENABLED.matcher(brandingHtml); if (matcher.find()) { String wakelockEnabledStr = matcher.group(1); wakelockEnabled = "true".equalsIgnoreCase(wakelockEnabledStr); } final List<String> externalUrlPatterns = new ArrayList<String>(); matcher = RegexPatterns.BRANDING_EXTERNAL_URLS.matcher(brandingHtml); while (matcher.find()) { externalUrlPatterns.add(matcher.group(1)); } FileOutputStream fos = new FileOutputStream(brandingFile); try { fos.write(brandingHtml.getBytes("UTF8")); } finally { fos.close(); } if (contentType != null && AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(contentType)) { brandingFile = new File(tmpBrandingDir, "embed.pdf"); } return new BrandingResult(tmpBrandingDir, brandingFile, watermarkFile, backgroundColor, menuItemColor, scheme, showHeader, dimension1, dimension2, contentType, wakelockEnabled, externalUrlPatterns); } finally { brandingBos.close(); } } catch (IOException e) { L.e(e); throw new BrandingFailureException("Error copying cached branded file to private space", e); } catch (NoSuchAlgorithmException e) { L.e(e); throw new BrandingFailureException("Cannot validate ", e); } }
From source file:com.aurel.track.dbase.HandleHome.java
public static String computeHash(File file) { try {//from w w w . jav a2 s . com MessageDigest md = MessageDigest.getInstance("MD5"); InputStream is = new FileInputStream(file); byte[] buffer = new byte[4096]; // To hold file contents DigestInputStream dis = new DigestInputStream(is, md); while (dis.read(buffer) != -1) { } byte[] digest = md.digest(); dis.close(); String hash = DatatypeConverter.printHexBinary(digest); return hash; } catch (Exception e) { } return null; }
From source file:com.aurel.track.dbase.HandleHome.java
public static String computeHash(URL url) { InputStream from = null;//from w ww . java 2 s . c o m String hash = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); from = url.openStream(); // Create input stream byte[] buffer = new byte[4096]; // To hold file contents DigestInputStream dis = new DigestInputStream(from, md); while (dis.read(buffer) != -1) { } byte[] digest = md.digest(); dis.close(); from.close(); hash = DatatypeConverter.printHexBinary(digest); } catch (Exception e) { LOGGER.error(e.getMessage()); } // Always close the stream, even if exceptions were thrown finally { if (from != null) try { from.close(); } catch (IOException e) { } } return hash; }
From source file:org.rascalmpl.library.Prelude.java
public IValue md5HashFile(ISourceLocation sloc, IEvaluatorContext ctx) { StringBuilder result = new StringBuilder(1024 * 1024); InputStream in = null;/*from w w w. j a v a 2 s . c o m*/ try { in = ctx.getResolverRegistry().getInputStream(sloc.getURI()); MessageDigest md = MessageDigest.getInstance("MD5"); in = new DigestInputStream(in, md); byte[] buf = new byte[4096]; int count; while ((count = in.read(buf)) != -1) { result.append(new java.lang.String(buf, 0, count)); } return values.string(new String(md.digest())); } catch (FileNotFoundException fnfex) { throw RuntimeExceptionFactory.pathNotFound(sloc, ctx.getCurrentAST(), null); } catch (IOException ioex) { throw RuntimeExceptionFactory.io(values.string(ioex.getMessage()), ctx.getCurrentAST(), null); } catch (NoSuchAlgorithmException e) { throw RuntimeExceptionFactory.io(values.string("Cannot load MD5 digest algorithm"), ctx.getCurrentAST(), null); } finally { if (in != null) { try { in.close(); } catch (IOException ioex) { throw RuntimeExceptionFactory.io(values.string(ioex.getMessage()), ctx.getCurrentAST(), null); } } } }
From source file:com.mobicage.rogerthat.plugins.messaging.BrandingMgr.java
private void extractJSEmbedding(final JSEmbeddingItemTO packet) throws BrandingFailureException, NoSuchAlgorithmException, FileNotFoundException, IOException { File brandingCache = getJSEmbeddingPacketFile(packet.name); if (!brandingCache.exists()) throw new BrandingFailureException("Javascript package not found!"); File jsRootDir = getJSEmbeddingRootDirectory(); if (!(jsRootDir.exists() || jsRootDir.mkdir())) throw new BrandingFailureException("Could not create private javascript dir!"); File jsPacketDir = getJSEmbeddingPacketDirectory(packet.name); if (jsPacketDir.exists() && !SystemUtils.deleteDir(jsPacketDir)) throw new BrandingFailureException("Could not delete existing javascript dir"); if (!jsPacketDir.mkdir()) throw new BrandingFailureException("Could not create javascript dir"); MessageDigest digester = MessageDigest.getInstance("SHA256"); DigestInputStream dis = new DigestInputStream(new BufferedInputStream(new FileInputStream(brandingCache)), digester);/*from w ww . j a v a2 s .co m*/ try { ZipInputStream zis = new ZipInputStream(dis); try { byte data[] = new byte[BUFFER_SIZE]; ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { L.d("Extracting: " + entry); int count = 0; if (entry.isDirectory()) { L.d("Skipping javascript dir " + entry.getName()); continue; } File destination = new File(jsPacketDir, entry.getName()); destination.getParentFile().mkdirs(); final OutputStream fos = new BufferedOutputStream(new FileOutputStream(destination), BUFFER_SIZE); try { while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) { fos.write(data, 0, count); } } finally { fos.close(); } } while (dis.read(data) >= 0) ; } finally { zis.close(); } } finally { dis.close(); } }