List of usage examples for java.security DigestInputStream DigestInputStream
public DigestInputStream(InputStream stream, MessageDigest digest)
From source file:com.jrummyapps.android.safetynet.SafetyNetHelper.java
@Nullable private String getApkDigestSha256() { try {/*from ww w. j a v a 2s. co m*/ FileInputStream fis = new FileInputStream(context.getPackageCodePath()); MessageDigest md = MessageDigest.getInstance(SHA_256); try { DigestInputStream dis = new DigestInputStream(fis, md); byte[] buffer = new byte[2048]; while (dis.read(buffer) != -1) { // } dis.close(); } finally { fis.close(); } return Base64.encodeToString(md.digest(), Base64.NO_WRAP); } catch (IOException | NoSuchAlgorithmException e) { return null; } }
From source file:hudson.Util.java
/** * Computes MD5 digest of the given input stream. * * @param source/*from w w w .j a v a 2s. com*/ * The stream will be closed by this method at the end of this method. * @return * 32-char wide string */ public static String getDigestOf(InputStream source) throws IOException { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[1024]; DigestInputStream in = new DigestInputStream(source, md5); try { while (in.read(buffer) > 0) ; // simply discard the input } finally { in.close(); } return toHexString(md5.digest()); } catch (NoSuchAlgorithmException e) { throw new IOException2("MD5 not installed", e); // impossible } }
From source file:org.robovm.eclipse.RoboVMPlugin.java
private static byte[] md5(InputStream in) throws IOException { MessageDigest digest;//from w w w . j a v a 2 s . c o m try { digest = MessageDigest.getInstance("md5"); } catch (NoSuchAlgorithmException e) { throw new Error(e); } DigestInputStream dis = new DigestInputStream(in, digest); IOUtils.copy(dis, new NullOutputStream()); return digest.digest(); }
From source file:org.eclipse.kura.deployment.rp.sh.impl.ShellScriptResourceProcessorImpl.java
private static byte[] computeDigest(InputStream is) throws NoSuchAlgorithmException, IOException { MessageDigest md = MessageDigest.getInstance("MD5"); DigestInputStream dis = new DigestInputStream(is, md); while (dis.read() != -1) { ;//ww w. j av a 2 s . c o m } byte[] digest = md.digest(); return digest; }
From source file:org.zanata.rest.service.raw.FileRawRestITCase.java
private String calculateFileHash(File srcFile) { try {/*from w w w . j a v a2 s .c om*/ // return Files.asByteSource(srcFile).hash(Hashing.md5()).toString(); MessageDigest md = MessageDigest.getInstance("MD5"); InputStream fileStream = new FileInputStream(srcFile); try { fileStream = new DigestInputStream(fileStream, md); byte[] buffer = new byte[256]; //noinspection StatementWithEmptyBody while (fileStream.read(buffer) > 0) { // just keep digesting the input } } finally { fileStream.close(); } //noinspection UnnecessaryLocalVariable String md5hash = new String(Hex.encodeHex(md.digest())); return md5hash; } catch (NoSuchAlgorithmException | IOException e) { throw new RuntimeException(e); } }
From source file:Hash.Hash.java
public static String getFullHash(File file) throws FileNotFoundException, IOException { MessageDigest md5Digest = null; try {//ww w .j a v a2 s . c o m md5Digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { return EMPTYHASH; } byte[] digestDef = md5Digest.digest(); byte[] digest = null; try (BufferedInputStream fileStream = new BufferedInputStream(new FileInputStream(file.toString())); DigestInputStream in = new DigestInputStream(fileStream, md5Digest);) { byte[] buffer = new byte[4096]; in.on(true); while (in.read(buffer) != -1) { } digest = md5Digest.digest(); } if (digest == null) { return EMPTYHASH; } if (Arrays.equals(digest, digestDef)) { return EMPTYHASH; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < digest.length; ++i) { sb.append(Integer.toHexString((digest[i] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); }
From source file:com.doculibre.constellio.feedprotocol.FeedProcessor.java
private ContentParse asContentParse(String url, List<FeedContent> feedContents, ConnectorInstance connectorInstance) { ConnectorInstanceServices connectorInstanceServices = ConstellioSpringUtils.getConnectorInstanceServices(); ContentParse contentParse = new ContentParse(); List<RecordMeta> metas = new ArrayList<RecordMeta>(); contentParse.setMetas(metas);/* www . ja v a2 s. co m*/ List<String> md5s = new ArrayList<String>(); StringBuffer contentBuffer = new StringBuffer(); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e1) { throw new RuntimeException(e1); } for (FeedContent feedContent : feedContents) { InputStream input = null; try { Metadata metadata = new Metadata(); ContentHandler handler = new BodyContentHandler(-1); ParseContext parseContext = new ParseContext(); if (feedContent.getEncoding() == FeedContent.ENCODING.BASE64BINARY) { input = new BufferedInputStream(new Base64InputStream( new FileInputStream(feedContent.getValue()), false, 80, new byte[] { (byte) '\n' })); } else { input = new BufferedInputStream(new FileInputStream(feedContent.getValue())); } // MD5 on the fly DigestInputStream dis = new DigestInputStream(input, md); if (connectorInstance.getConnectorType().getName().equals("mailbox-connector")) { // FIXME : a supprimer et ajouter un Detector qui detecte // correctement les fichiers eml // CompositeParser parser = new AutoDetectParser(); // Map<String, Parser> parsers = parser.getParsers(); // parsers.put("text/plain", new // EmlParser());//message/rfc822 // parser.setParsers(parsers); // Autre pb avec detection des fichiers eml Parser parser = new EmlParser(); parser.parse(dis, handler, metadata, parseContext); } else { // IOUtils.copy(input, new FileOutputStream(new // File("C:/tmp/test.pdf"))); PARSER.parse(dis, handler, metadata, parseContext); } md5s.add(Base64.encodeBase64String(md.digest())); for (String name : metadata.names()) { for (String content : metadata.getValues(name)) { if (!"null".equals(content)) { RecordMeta meta = new RecordMeta(); ConnectorInstanceMeta connectorInstanceMeta = connectorInstance.getOrCreateMeta(name); if (connectorInstanceMeta.getId() == null) { connectorInstanceServices.makePersistent(connectorInstance); } meta.setConnectorInstanceMeta(connectorInstanceMeta); meta.setContent(content); metas.add(meta); } } } String contentString = handler.toString(); // remove the duplication of white space, Bin contentBuffer.append(contentString.replaceAll("(\\s){2,}", "$1")); } catch (Throwable e) { LOG.warning("Could not parse document " + StringUtils.defaultString(url) + " for connector : " + connectorInstance.getName() + " Message: " + e.getMessage()); } finally { IOUtils.closeQuietly(input); if (feedContent != null) { FileUtils.deleteQuietly(feedContent.getValue()); } } } contentParse.setContent(contentBuffer.toString()); contentParse.setMd5(md5s); return contentParse; }
From source file:Hash.Hash.java
public static String getHash(File file) throws FileNotFoundException, IOException { MessageDigest md5Digest = null; try {/*from w w w.jav a 2 s . c o m*/ md5Digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { return EMPTYHASH; } byte[] digestDef = md5Digest.digest(); byte[] digest = null; String ext = FilenameUtils.getExtension(file.getName().toLowerCase()); if (ext.equals("arw") || ext.equals("nef") || ext.equals("dng") || ext.equals("tif") || ext.equals("tiff")) { // <editor-fold defaultstate="collapsed" desc="raw"> try (BufferedInputStream rawIn = new BufferedInputStream(new FileInputStream(file.toString()));) { digest = startOfScanTiff(file, rawIn); } catch (IOException e) { errorOut("Hash", e); } // </editor-fold> } else { try (FileInputStream fileInStream = new FileInputStream(file.toString()); BufferedInputStream fileStream = new BufferedInputStream(fileInStream); DigestInputStream in = new DigestInputStream(fileStream, md5Digest);) { byte[] buffer = new byte[4096]; long length; switch (ext) { // <editor-fold defaultstate="collapsed" desc="mp4"> case "mp4": in.on(false); boolean EOF = false; do { length = readEndianValue(in, 4, false) - 8; // byte boxLength[] = readBytes(in, 4); String desc = new String(readBytes(in, 4)); // ByteBuffer wrapped = ByteBuffer.wrap(boxLength); // big-endian by default // length = wrapped.getInt() - 8; if (length == -7) { //largesize length = readEndianValue(in, 8, false) - 16; } else if (length == -8) { // until eof EOF = true; } else if (length == in.available()) { EOF = true; } if (desc.equals("mdat")) { in.on(true); while (buffer.length <= length) { int read = in.read(buffer); length -= read; } while (length > 0) { int read = in.read(buffer, 0, (int) length); if (read == -1) { digest = null; break; } length -= read; } // break; } else { if (!skipBytes(in, length)) break; } } while (!EOF); digest = md5Digest.digest(); break; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="JPG"> case "jpg": case "jpeg": int scanLength; int scanLengthOld = 0; do { in.on(false); md5Digest.reset(); scanLength = 0; if (startOfScanJPG(fileStream) == -1) break; in.on(true); int c = 0; int oldc; do { oldc = c; c = in.read(); if (c == -1) { return EMPTYHASH; } scanLength++; } while (!(oldc == 0xFF && c == 0xD9/*217*/)); if (scanLength > scanLengthOld) { digest = md5Digest.digest(); scanLengthOld = scanLength; } } while (scanLengthOld < in.available()); break; // </editor-fold> default: in.on(true); while (in.read(buffer) != -1) { } digest = md5Digest.digest(); break; } } catch (IOException e) { errorOut("Hash", e); } } if (digest == null) { return EMPTYHASH; } if (Arrays.equals(digest, digestDef)) { return EMPTYHASH; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < digest.length; ++i) { sb.append(Integer.toHexString((digest[i] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); }
From source file:net.mozq.picto.core.ProcessCore.java
private static ProcessDataStatus process(ProcessCondition processCondition, ProcessData processData, Function<ProcessData, ProcessDataStatus> overwriteConfirm) throws IOException { ProcessDataStatus status;// w w w . j a v a 2 s . c o m Path destParentPath = processData.getDestPath().getParent(); if (destParentPath != null) { Files.createDirectories(destParentPath); } if (processCondition.isCheckDigest() || (processCondition.isChangeExifDate() && processData.getBaseDate() != null) || processCondition.isRemveExifTagsGps() || processCondition.isRemveExifTagsAll()) { Path destTempPath = null; try { destTempPath = Files.createTempFile(processData.getDestPath().getParent(), processData.getDestPath().getFileName().toString(), null); if (processCondition.isCheckDigest()) { String algorithm = FILE_DIGEST_ALGORITHM; MessageDigest srcMD = newMessageDigest(algorithm); try (InputStream is = new DigestInputStream( new BufferedInputStream(Files.newInputStream(processData.getSrcPath())), srcMD)) { Files.copy(is, destTempPath, OPTIONS_COPY_REPLACE); } byte[] srcDigest = srcMD.digest(); MessageDigest destMD = newMessageDigest(algorithm); try (InputStream is = new DigestInputStream( new BufferedInputStream(Files.newInputStream(destTempPath)), destMD)) { byte[] b = new byte[1024]; while (is.read(b) != -1) { } } byte[] destDigest = destMD.digest(); if (!isSame(srcDigest, destDigest)) { throw new PictoFileDigestMismatchException( Messages.getString("message.error.digest.mismatch")); } } else if (processCondition.isRemveExifTagsAll()) { ExifRewriter exifRewriter = new ExifRewriter(); try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(destTempPath))) { exifRewriter.removeExifMetadata(processData.getSrcPath().toFile(), os); } catch (ImageReadException | ImageWriteException e) { throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e); } } else if (processCondition.isChangeExifDate() || processCondition.isRemveExifTagsGps()) { ImageMetadata imageMetadata = getImageMetadata(processData.getSrcPath()); TiffOutputSet outputSet = getOutputSet(imageMetadata); if (outputSet == null) { Files.copy(processData.getSrcPath(), destTempPath, OPTIONS_COPY_REPLACE); } else { if (processCondition.isChangeExifDate()) { SimpleDateFormat exifDateFormat = new SimpleDateFormat(EXIF_DATE_PATTERN); exifDateFormat.setTimeZone(processCondition.getTimeZone()); String exifBaseDate = exifDateFormat.format(processData.getBaseDate()); DecimalFormat exifSubsecFormat = new DecimalFormat(EXIF_SUBSEC_PATTERN); String exifBaseSubsec = exifSubsecFormat .format((int) (processData.getBaseDate().getTime() / 10) % 100); try { TiffOutputDirectory rootDirectory = outputSet.getRootDirectory(); TiffOutputDirectory exifDirectory = outputSet.getExifDirectory(); if (rootDirectory != null) { rootDirectory.removeField(TiffTagConstants.TIFF_TAG_DATE_TIME); rootDirectory.add(TiffTagConstants.TIFF_TAG_DATE_TIME, exifBaseDate); } if (exifDirectory != null) { exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME); exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME, exifBaseSubsec); exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL); exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL, exifBaseDate); exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL); exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL, exifBaseSubsec); exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED); exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED, exifBaseDate); exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED); exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED, exifBaseSubsec); } } catch (ImageWriteException e) { throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e); } } if (processCondition.isRemveExifTagsGps()) { outputSet.removeField(ExifTagConstants.EXIF_TAG_GPSINFO); } ExifRewriter exifRewriter = new ExifRewriter(); try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(destTempPath))) { exifRewriter.updateExifMetadataLossless(processData.getSrcPath().toFile(), os, outputSet); } catch (ImageReadException | ImageWriteException e) { throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e); } } } Path destPath; if (processCondition.getOperationType() == OperationType.Overwrite) { destPath = processData.getSrcPath(); } else { destPath = processData.getDestPath(); } try { Files.move(destTempPath, destPath, OPTIONS_MOVE); if (processCondition.getOperationType() == OperationType.Move) { Files.deleteIfExists(processData.getSrcPath()); } status = ProcessDataStatus.Success; } catch (FileAlreadyExistsException e) { status = confirmOverwrite(processCondition, processData, overwriteConfirm); if (status == ProcessDataStatus.Processing) { // Overwrite Files.move(destTempPath, destPath, OPTIONS_MOVE_REPLACE); if (processCondition.getOperationType() == OperationType.Move) { Files.deleteIfExists(processData.getSrcPath()); } status = ProcessDataStatus.Success; } } } finally { if (destTempPath != null) { Files.deleteIfExists(destTempPath); } } } else { switch (processCondition.getOperationType()) { case Copy: try { Files.copy(processData.getSrcPath(), processData.getDestPath(), OPTIONS_COPY); status = ProcessDataStatus.Success; } catch (FileAlreadyExistsException e) { status = confirmOverwrite(processCondition, processData, overwriteConfirm); if (status == ProcessDataStatus.Processing) { Files.copy(processData.getSrcPath(), processData.getDestPath(), OPTIONS_COPY_REPLACE); status = ProcessDataStatus.Success; } } break; case Move: try { Files.move(processData.getSrcPath(), processData.getDestPath(), OPTIONS_MOVE); status = ProcessDataStatus.Success; } catch (FileAlreadyExistsException e) { status = confirmOverwrite(processCondition, processData, overwriteConfirm); if (status == ProcessDataStatus.Processing) { Files.move(processData.getSrcPath(), processData.getDestPath(), OPTIONS_MOVE_REPLACE); status = ProcessDataStatus.Success; } } break; case Overwrite: // NOP status = ProcessDataStatus.Success; break; default: throw new IllegalStateException(processCondition.getOperationType().toString()); } } if (status == ProcessDataStatus.Success) { FileTime creationFileTime = processData.getSrcFileAttributes().creationTime(); FileTime modifiedFileTime = processData.getSrcFileAttributes().lastModifiedTime(); FileTime accessFileTime = processData.getSrcFileAttributes().lastAccessTime(); if (processCondition.isChangeFileCreationDate() || processCondition.isChangeFileModifiedDate() || processCondition.isChangeFileAccessDate()) { if (processData.getBaseDate() != null) { FileTime baseFileTime = FileTime.fromMillis(processData.getBaseDate().getTime()); if (processCondition.isChangeFileCreationDate()) { creationFileTime = baseFileTime; } if (processCondition.isChangeFileModifiedDate()) { modifiedFileTime = baseFileTime; } if (processCondition.isChangeFileAccessDate()) { accessFileTime = baseFileTime; } } } BasicFileAttributeView attributeView = Files.getFileAttributeView(processData.getDestPath(), BasicFileAttributeView.class); attributeView.setTimes(modifiedFileTime, accessFileTime, creationFileTime); } return status; }