Exemplo n.º 1
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 "";
    }
  }
Exemplo n.º 2
0
  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");
    }
  }
Exemplo n.º 3
0
  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);
        }
      }
    }
  }
Exemplo n.º 4
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())});
  }
 /**
  * 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());
 }
Exemplo n.º 6
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);
   }
 }
  /**
   * 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) {
      }
    }
  }