コード例 #1
0
ファイル: FileUtils.java プロジェクト: DicomFlow/repos
  public static void verifyMD5(File file, String originalMd5) throws Exception {
    log.info("M-READ file:" + file);
    MessageDigest md = MessageDigest.getInstance("MD5");

    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));

    DigestInputStream dis = new DigestInputStream(in, md);
    try {
      DcmParser parser = DcmParserFactory.getInstance().newDcmParser(dis);
      parser.parseDcmFile(FileFormat.DICOM_FILE, Tags.PixelData);
      if ((parser.getReadTag() & 0xFFFFFFFFL) >= Tags.PixelData) {
        if (parser.getReadLength() == -1) {
          while (parser.parseHeader() == Tags.Item) {
            readOut(parser.getInputStream(), parser.getReadLength());
          }
        }
        readOut(parser.getInputStream(), parser.getReadLength());
        parser.parseDataset(parser.getDcmDecodeParam(), -1);
      }
    } finally {
      try {
        dis.close();
      } catch (IOException ignore) {
      }
    }
    byte[] md5 = md.digest();
    if (!Arrays.equals(md5, MD5.toBytes(originalMd5))) {
      log.error(
          "MD5 for "
              + file.getAbsolutePath()
              + " is different that expected.  Has the file been changed or corrupted?");
      throw new IllegalStateException("MD5 mismatch");
    }
  }
コード例 #2
0
  /**
   * @param f обрабатываемый файл
   * @return MD5 файла, если вызвано исключение возвращает пустую строку
   */
  public static String getMD5(File f) {
    try {
      MessageDigest algorithm = MessageDigest.getInstance("MD5");

      FileInputStream fis = new FileInputStream(f.toString());
      BufferedInputStream bis = new BufferedInputStream(fis);
      DigestInputStream dis = new DigestInputStream(bis, algorithm);

      while (dis.read() != -1) ;

      byte[] hash = algorithm.digest();
      dis.close();

      Formatter formatter = new Formatter();

      for (byte b : hash) {
        formatter.format("%02x", b);
      }

      try {
        return formatter.toString();
      } finally {
        formatter.close();
      }
    } catch (Exception e) {
      return "";
    }
  }
コード例 #3
0
ファイル: FileDigestTest.java プロジェクト: redbrick9/liquid
 @Test
 public void testDigest() throws NoSuchAlgorithmException, IOException {
   MessageDigest md = MessageDigest.getInstance("MD5");
   try (DigestInputStream in =
       new DigestInputStream(
           this.getClass().getClassLoader().getResourceAsStream("processes/liquid.poc.bpmn20.xml"),
           md)) {
     byte[] content = new byte[in.available()];
     in.read(content);
   }
   byte[] checksum = md.digest();
   System.out.println(StringUtil.encodeHex(checksum));
 }
コード例 #4
0
ファイル: AtsUtils.java プロジェクト: xudongyi/yungouweb
 public static boolean checkMd5sum(File file, String checkCode) throws IOException {
   DigestInputStream dInput = null;
   try {
     FileInputStream fInput = new FileInputStream(file);
     dInput = new DigestInputStream(fInput, getMd5Instance());
     byte[] buf = new byte[8192];
     while (dInput.read(buf) > 0) {}
     byte[] bytes = dInput.getMessageDigest().digest();
     return bytes2hex(bytes).equals(checkCode);
   } finally {
     closeQuietly(dInput);
   }
 }
コード例 #5
0
ファイル: DigestInput.java プロジェクト: skanjo/oliverlee
  public static void main(String args[]) throws Exception {
    MessageDigest m = MessageDigest.getInstance("MD5");
    FileInputStream fin = new FileInputStream(args[0]);
    //	BufferedInputStream bin=new BufferedInputStream(fin);
    DigestInputStream din = new DigestInputStream(fin, m);
    while (din.read() != -1) ;

    byte s[] = m.digest();
    String result = "";
    for (int i = 0; i < s.length; i++) {
      result += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6);
    }
    System.out.println(result);
  }
コード例 #6
0
ファイル: Hash.java プロジェクト: h-s-r/Lehirti-Game-Engine
  public static String calculateSHA1(final File file) {
    final MessageDigest sha1;
    try {
      sha1 = MessageDigest.getInstance("SHA1");
    } catch (final NoSuchAlgorithmException e) {
      LOGGER.error("Hash algorithm SHA1 missing", e);
      return null;
    }

    FileInputStream fis = null;
    BufferedInputStream bis = null;
    DigestInputStream dis = null;
    try {
      fis = new FileInputStream(file);
      bis = new BufferedInputStream(fis);
      dis = new DigestInputStream(bis, sha1);

      // update hash
      while (dis.read() != -1) {}

      return toHex(sha1.digest());
    } catch (final Exception e) {
      LOGGER.error("Unable to compute SHA1-hash for " + file.getAbsolutePath(), e);
      return null;
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (final IOException e) {
          LOGGER.error("Unable to close file input stream for file " + file.getAbsolutePath(), e);
        }
      }
      if (bis != null) {
        try {
          bis.close();
        } catch (final IOException e) {
          LOGGER.error(
              "Unable to close buffered input stream for file " + file.getAbsolutePath(), e);
        }
      }
      if (dis != null) {
        try {
          dis.close();
        } catch (final IOException e) {
          LOGGER.error("Unable to close digest input stream for file " + file.getAbsolutePath(), e);
        }
      }
    }
  }
コード例 #7
0
  public static String getMd5(File file) {
    DigestInputStream stream = null;
    try {
      stream =
          new DigestInputStream(
              new java.io.FileInputStream(file), MessageDigest.getInstance("MD5"));
      byte[] buffer = new byte[' '];
      while (stream.read(buffer) != -1) {}
      stream.close();
    } catch (Exception ignored) {
      return null;
    }

    return String.format(
        "%1$032x", new Object[] {new BigInteger(1, stream.getMessageDigest().digest())});
  }
コード例 #8
0
 /**
  * Creates a Fingerprint based on the contents of a file.
  *
  * <p>Note that this will close() stream after calculating the digest.
  *
  * @param byteCount length of original data will be stored at byteCount[0] as a side product of
  *     the fingerprint calculation
  */
 public static Fingerprint fromInputStream(InputStream stream, long[] byteCount)
     throws IOException {
   DigestInputStream in = null;
   long count = 0;
   try {
     in = new DigestInputStream(stream, DIGESTER);
     byte[] bytes = new byte[8192];
     while (true) {
       // scan through file to compute a fingerprint.
       int n = in.read(bytes);
       if (n < 0) break;
       count += n;
     }
   } finally {
     if (in != null) in.close();
   }
   if ((byteCount != null) && (byteCount.length > 0)) byteCount[0] = count;
   return new Fingerprint(in.getMessageDigest().digest());
 }
コード例 #9
0
 @Override
 public byte[] digestFile(File file) {
   try {
     MessageDigest md = MessageDigest.getInstance(this.algorithm);
     FileInputStream fileIS = new FileInputStream(file);
     BufferedInputStream bis = new BufferedInputStream(fileIS);
     DataInputStream dis = new DataInputStream(bis);
     DigestInputStream digin = new DigestInputStream(dis, md);
     byte[] buffer = new byte[BUFSIZE];
     while (digin.read(buffer, 0, BUFSIZE) != -1) ;
     digin.close();
     return md.digest();
   } catch (NoSuchAlgorithmException e) {
     throw new CriptographyException("Failed to set algorithm", e);
   } catch (FileNotFoundException e) {
     throw new CriptographyException("File [" + file + "] not found", e);
   } catch (IOException e) {
     throw new CriptographyException("Error reading file [" + file + "]", e);
   }
 }
コード例 #10
0
ファイル: HashSum.java プロジェクト: fviale/programming
  public static String hashsum(File file, String encoding)
      throws IOException, NoSuchAlgorithmException {
    FileInputStream fis = new FileInputStream(file);
    MessageDigest md = MessageDigest.getInstance(encoding);

    try {
      DigestInputStream dis = new DigestInputStream(fis, md);
      byte[] buffer = new byte[8192];
      while (dis.read(buffer) != -1) ;
    } finally {
      fis.close();
    }

    byte[] bDigest = md.digest();
    String res = "";
    for (byte b : bDigest) {
      res += Integer.toHexString(b & 0xFF);
    }

    return res;
  }
コード例 #11
0
 @Override
 public UploadedFileInfo call() throws Exception {
   UploadedFileInfo ufi;
   Path targetFile = createTempFile();
   StopWatch sw = new StopWatch();
   sw.start();
   try {
     LOGGER.debug(
         "Saving {} ({}) Expected MD5:{}...",
         targetFile.toString(),
         Util.byteCountToDisplaySize(expectedLength),
         expectedMd5);
     this.actualLength = saveStreamToFile(this.dis, targetFile);
     this.actualMd5 = Hex.encodeHexString(dis.getMessageDigest().digest());
     verifyExpecteds();
     ufi = new UploadedFileInfo(targetFile, this.actualLength, this.actualMd5);
     sw.stop();
     LOGGER.debug(
         "Saved {} ({}) Computed MD5:{}, Time: {}, Speed: {}",
         ufi.getFilepath().toString(),
         Util.byteCountToDisplaySize(ufi.getSize()),
         ufi.getMd5(),
         sw.getTimeElapsedFormatted(),
         sw.getRate(ufi.getSize()));
   } catch (Exception e) {
     LOGGER.error(
         "Error saving {} ({} bytes) Expected MD5:{} - {}",
         targetFile.toString(),
         this.expectedLength,
         this.expectedMd5,
         e.getMessage());
     throw e;
   } finally {
     IOUtils.closeQuietly(dis);
   }
   return ufi;
 }
コード例 #12
0
  /**
   * Get bytes from an InputStream.
   *
   * @param is
   * @param md5Hash
   * @return An byte array containing all the bytes read from the InputStream. <code>null</code> is
   *     returned if error occurred when reading inputs.
   * @throws SocketTimeoutException
   * @throws IllegalAccessException MD5 error.
   */
  public static byte[] get(InputStream is, String md5Hash)
      throws SocketTimeoutException, IllegalAccessException {
    // Read the response from server
    byte[] returnedBytes = null;
    byte[] buffer = new byte[128];
    LinkedList<byte[]> downloadedList = new LinkedList<byte[]>();

    int len;
    int downloaded = 0; // The total length of downloaded bytes.
    try {
      while (true) {
        // Read from stream.
        len = is.read(buffer);

        if (len == -1) {
          // Reading ends.
          break;
        } else {
          byte[] currentBytes = new byte[len];
          System.arraycopy(buffer, 0, currentBytes, 0, len);
          downloadedList.add(currentBytes);
        }
        downloaded += len;
      }

      // Construct the returned byte array by collecting all the bytes from the list.
      returnedBytes = new byte[downloaded];
      int copiedIndex = 0;
      Iterator<byte[]> list = downloadedList.iterator();
      while (list.hasNext()) {
        byte[] currentBytes = list.next();
        System.arraycopy(currentBytes, 0, returnedBytes, copiedIndex, currentBytes.length);
        copiedIndex += currentBytes.length;
      }

      // If MD5 is given, check the stream result.
      if (md5Hash != null && md5Hash.length() > 0) {
        // System.out.println("[StreamReader] Check MD5");
        ByteArrayInputStream bais = null;
        DigestInputStream dis = null;
        MessageDigest digest = null;
        try {
          digest = MessageDigest.getInstance("MD5");
          bais = new ByteArrayInputStream(returnedBytes);
          dis = new DigestInputStream(bais, digest);

          while (dis.read(buffer) > 0) {}

          String receiveMD5 = Hex.toHexString(digest.digest());
          if (receiveMD5.compareToIgnoreCase(md5Hash) != 0)
            throw new IllegalAccessException("The MD5 of the request body is not correct.");
          // else
          //	System.out.println("[StreamReader] MD5 OK.");
        } catch (NoSuchAlgorithmException e) {
          e.printStackTrace();
        } finally {
          if (dis != null) dis.close();
          if (bais != null) bais.close();
        }
      }

      return returnedBytes;
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    } finally {
      try {
        if (is != null) is.close();
      } catch (Exception e) {
      }
    }
  }