Java Code Examples for java.security.DigestInputStream#read()

The following examples show how to use java.security.DigestInputStream#read() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Util.java    From java-n-IDE-for-Android with Apache License 2.0 7 votes vote down vote up
/**
 * @source http://stackoverflow.com/a/304350
 */
private static byte[] hash(String alg, InputStream in) throws Exception {
    MessageDigest md = MessageDigest.getInstance(alg);
    DigestInputStream dis = new DigestInputStream(new BufferedInputStream(in), md);
    try {
        byte[] buffer = new byte[1024];
        while (true) {
            int readCount = dis.read(buffer);
            if (readCount < 0) {
                break;
            }
        }
        return md.digest();
    } finally {
        in.close();
    }
}
 
Example 2
Source File: AbstractAwsSigner.java    From aws-sdk-java-v2 with Apache License 2.0 7 votes vote down vote up
byte[] hash(InputStream input) throws SdkClientException {
    try {
        MessageDigest md = getMessageDigestInstance();
        @SuppressWarnings("resource")
        DigestInputStream digestInputStream = new SdkDigestInputStream(
                input, md);
        byte[] buffer = new byte[1024];
        while (digestInputStream.read(buffer) > -1) {
            ;
        }
        return digestInputStream.getMessageDigest().digest();
    } catch (Exception e) {
        throw SdkClientException.builder()
                                .message("Unable to compute hash while signing request: " + e.getMessage())
                                .cause(e)
                                .build();
    }
}
 
Example 3
Source File: FileSnippet.java    From mobly-bundled-snippets with Apache License 2.0 6 votes vote down vote up
@Rpc(description = "Compute MD5 hash on a content URI. Return the MD5 has has a hex string.")
public String fileMd5Hash(String uri) throws IOException, NoSuchAlgorithmException {
    Uri uri_ = Uri.parse(uri);
    ParcelFileDescriptor pfd = mContext.getContentResolver().openFileDescriptor(uri_, "r");
    MessageDigest md = MessageDigest.getInstance("MD5");
    int length = (int) pfd.getStatSize();
    byte[] buf = new byte[length];
    ParcelFileDescriptor.AutoCloseInputStream stream =
            new ParcelFileDescriptor.AutoCloseInputStream(pfd);
    DigestInputStream dis = new DigestInputStream(stream, md);
    try {
        dis.read(buf, 0, length);
        return Utils.bytesToHexString(md.digest());
    } finally {
        dis.close();
        stream.close();
    }
}
 
Example 4
Source File: HttpProxyTask.java    From open-rmbt with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param inputStream
 * @return
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
public static Md5Result generateChecksum(InputStream inputStream) throws NoSuchAlgorithmException, IOException {
	Md5Result md5 = new Md5Result();
	MessageDigest md = MessageDigest.getInstance("MD5");
	DigestInputStream dis = new DigestInputStream(inputStream, md);
	
	byte[] dataBytes = new byte[4096];
      
       int nread = 0; 
       while ((nread = dis.read(dataBytes)) != -1) {
       	md5.contentLength += nread;
       };
       
       dis.close();
       
       long startNs = System.nanoTime();
       md5.md5 = generateChecksumFromDigest(md.digest());
       md5.generatingTimeNs = System.nanoTime() - startNs;
       
       return md5;
}
 
Example 5
Source File: Util.java    From zencash-swing-wallet-ui with MIT License 6 votes vote down vote up
public static byte[] calculateSHA256Digest(byte[] input)
    throws IOException 
{
    try 
    {
        MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
        DigestInputStream dis = new DigestInputStream(new ByteArrayInputStream(input), sha256);
        byte [] temp = new byte[0x1 << 13];
        byte[] digest;
        while(dis.read(temp) >= 0);
        {
            digest = sha256.digest();
        }
        
        return digest;
    } catch (NoSuchAlgorithmException impossible) 
    {
        throw new IOException(impossible);
    }
}
 
Example 6
Source File: ShimLoader.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
static String md5sum(InputStream input) throws IOException {
  BufferedInputStream in = new BufferedInputStream(input);

  try {
    MessageDigest digest = MessageDigest.getInstance("MD5");
    DigestInputStream digestInputStream = new DigestInputStream(in, digest);
    boolean bytesRead = false;
    byte[] buffer = new byte[8192];

    while(digestInputStream.read(buffer) != -1) {
      // CHECKSTYLE:OFF EmptyStatement
      ;
      // CHECKSTYLE:ON
    }

    ByteArrayOutputStream md5out = new ByteArrayOutputStream();
    md5out.write(digest.digest());
    String md5String = md5out.toString();
    return md5String;
  } catch (NoSuchAlgorithmException noSuchAlgorithmException) {
    throw new IllegalStateException("MD5 algorithm is not available: " + noSuchAlgorithmException);
  } finally {
    in.close();
  }
}
 
Example 7
Source File: DigestInputStreamTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Test #4 for <code>read(byte[],int,int)</code> method<br>
 *
 * Assertion: returns the number of bytes read<br>
 *
 * Assertion: updates associated digest<br>
 */
public final void testReadbyteArrayintint04()
    throws IOException {
    for (int ii=0; ii<algorithmName.length; ii++) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithmName[ii]);
            InputStream is = new ByteArrayInputStream(myMessage);
            DigestInputStream dis = new DigestInputStream(is, md);
            byte[] bArray = new byte[MY_MESSAGE_LEN];
            // read all but EOS
            dis.read(bArray, 0, bArray.length);
            // check that subsequent read(byte[],int,int) calls return -1 (EOS)
            assertEquals("retval1", -1, dis.read(bArray, 0, 1));
            assertEquals("retval2", -1, dis.read(bArray, 0, bArray.length));
            assertEquals("retval3", -1, dis.read(bArray, 0, 1));
            // check that 3 previous read() calls did not update digest
            assertTrue("update",
                    Arrays.equals(dis.getMessageDigest().digest(),
                            MDGoldenData.getDigest(algorithmName[ii])));
            return;
        } catch (NoSuchAlgorithmException e) {
            // allowed failure
        }
    }
    fail(getName() + ": no MessageDigest algorithms available - test not performed");
}
 
Example 8
Source File: Rd5DiffManager.java    From brouter with MIT License 6 votes vote down vote up
public static String getMD5( File f ) throws Exception
{
  MessageDigest md = MessageDigest.getInstance("MD5");
  BufferedInputStream bis = new BufferedInputStream( new FileInputStream( f ) );
  DigestInputStream dis = new DigestInputStream(bis, md);
  byte[] buf = new byte[8192];
  for(;;)
  {
    int len = dis.read( buf );
    if ( len <= 0 )
    {
      break;
    }
  }
  dis.close();
  byte[] bytes = md.digest();

  StringBuilder sb = new StringBuilder();
  for (int j = 0; j < bytes.length; j++)
  {
    int v = bytes[j] & 0xff;
    sb.append( hexChar( v >>> 4 ) ).append( hexChar( v & 0xf ) );
  }
  return sb.toString();
}
 
Example 9
Source File: MD5Hash.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @source http://stackoverflow.com/a/304350
 */
private static byte[] hash(String alg, InputStream in) throws Exception {
    MessageDigest md = MessageDigest.getInstance(alg);
    DigestInputStream dis = new DigestInputStream(new BufferedInputStream(in), md);
    try {
        byte[] buffer = new byte[1024];
        while (true) {
            int readCount = dis.read(buffer);
            if (readCount < 0) {
                break;
            }
        }
        return md.digest();
    } finally {
        in.close();
    }
}
 
Example 10
Source File: ProvingKeyFetcher.java    From hush-swing-wallet-ui with MIT License 6 votes vote down vote up
private static boolean checkSHA256(final File provingKey, final Component parent) throws IOException {
    final MessageDigest sha256;
    try {
        sha256 = MessageDigest.getInstance("SHA-256");
    } catch (final NoSuchAlgorithmException impossible) {
        throw new RuntimeException(impossible);
    }
    try (final InputStream is = new BufferedInputStream(new FileInputStream(provingKey))) {
        final ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(parent, "Verifying proving key", is);
        pmis.getProgressMonitor().setMaximum(PROVING_KEY_SIZE);
        pmis.getProgressMonitor().setMillisToPopup(10);
        final DigestInputStream dis = new DigestInputStream(pmis, sha256);
        final byte[] temp = new byte[0x1 << 13];
        while (dis.read(temp) >= 0) {
            /* do the thing */
        }
        final byte[] digest = sha256.digest();
        return SHA256.equalsIgnoreCase(DatatypeConverter.printHexBinary(digest));
    }
}
 
Example 11
Source File: Controller.java    From onos with Apache License 2.0 6 votes vote down vote up
public byte[] getSha1Checksum(String filepath) {
    if (filepath == null) {
        return new byte[0];
    }
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA1");
        File f = new File(filepath);
        FileInputStream is = new FileInputStream(f);
        DigestInputStream dis = new DigestInputStream(is, digest);
        byte[] buffer = new byte[1024];
        while (dis.read(buffer) > 0) {
            // nothing to do :)
        }
        is.close();
        return dis.getMessageDigest().digest();
    } catch (NoSuchAlgorithmException ignored) {
    } catch (IOException e) {
        log.info("Error reading file file: {}", filepath);
    }
    return new byte[0];
}
 
Example 12
Source File: AbstractSigner.java    From jdcloud-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * 方法描述:计算hash值
 * @param input
 * @return
 * @throws SdkClientException 
 * @author lixuenan3
 * @date 2018年3月22日 下午3:26:35
 */
protected byte[] hash(InputStream input) throws SdkClientException {
    try {
        MessageDigest md = getMessageDigestInstance();
        @SuppressWarnings("resource")
        DigestInputStream digestInputStream = new SdkDigestInputStream(
                input, md);
        byte[] buffer = new byte[1024];
        while (digestInputStream.read(buffer) > -1) {
            ;
        }
        return digestInputStream.getMessageDigest().digest();
    } catch (Exception e) {
        throw new SdkClientException(
                "Unable to compute hash while signing request: "
                        + e.getMessage(), e);
    }
}
 
Example 13
Source File: FileUtils.java    From sofa-ark with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a SHA.1 Hash for a given file.
 * @param file the file to hash
 * @return the hash value as a String
 * @throws IOException if the file cannot be read
 */
public static String sha1Hash(File file) throws IOException {
    try {
        DigestInputStream inputStream = new DigestInputStream(new FileInputStream(file),
            MessageDigest.getInstance("SHA-1"));
        try {
            byte[] buffer = new byte[4098];
            while (inputStream.read(buffer) != -1) { //NOPMD
                // Read the entire stream
            }
            return bytesToHex(inputStream.getMessageDigest().digest());
        } finally {
            inputStream.close();
        }
    } catch (NoSuchAlgorithmException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example 14
Source File: DigestInputStreamTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Test #3 for <code>read()</code> method<br>
 * Test #1 for <code>on(boolean)</code> method<br>
 *
 * Assertion: <code>read()</code> must not update digest if it is off<br>
 * Assertion: <code>on(boolean)</code> turns digest functionality on
 * (if <code>true</code> passed as a parameter) or off (if <code>false</code>
 *  passed)
 */
public final void testRead03()
    throws IOException {
    for (int ii=0; ii<algorithmName.length; ii++) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithmName[ii]);
            InputStream is = new ByteArrayInputStream(myMessage);
            DigestInputStream dis = new DigestInputStream(is, md);

            // turn digest off
            dis.on(false);

            for (int i=0; i<MY_MESSAGE_LEN; i++) {
                dis.read();
            }

            // check that digest value has not been updated by read()
            assertTrue(Arrays.equals(dis.getMessageDigest().digest(),
                    MDGoldenData.getDigest(algorithmName[ii]+"_NU")));
            return;
        } catch (NoSuchAlgorithmException e) {
            // allowed failure
        }
    }
    fail(getName() + ": no MessageDigest algorithms available - test not performed");
}
 
Example 15
Source File: Utils.java    From sheepit-client with GNU General Public License v2.0 6 votes vote down vote up
public static String md5(String path_of_file_) {
	try {
		MessageDigest md = MessageDigest.getInstance("MD5");
		InputStream is = Files.newInputStream(Paths.get(path_of_file_));
		DigestInputStream dis = new DigestInputStream(is, md);
		byte[] buffer = new byte[8192];
		while (dis.read(buffer) > 0)
			; // process the entire file
		String data = DatatypeConverter.printHexBinary(md.digest()).toLowerCase();
		dis.close();
		is.close();
		return data;
	}
	catch (NoSuchAlgorithmException | IOException e) {
		return "";
	}
}
 
Example 16
Source File: ArgbRendererTest.java    From render with GNU General Public License v2.0 6 votes vote down vote up
public static String getDigestString(final File file) throws Exception {
    final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
    final FileInputStream fileInputStream = new FileInputStream(file);
    final DigestInputStream digestInputStream = new DigestInputStream(fileInputStream, messageDigest);

    final byte[] buffer = new byte[8192];
    for (int bytesRead = 1; bytesRead > 0;) {
        bytesRead = digestInputStream.read(buffer);
    }

    final byte[] digestValue = messageDigest.digest();
    final StringBuilder sb = new StringBuilder(digestValue.length);
    for (final byte b : digestValue) {
        sb.append(b);
    }

    return sb.toString();
}
 
Example 17
Source File: Main.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/** Display the location and checksum of a class. */
void showClass(String className) {
    PrintWriter pw = log.getWriter(WriterKind.NOTICE);
    pw.println("javac: show class: " + className);
    URL url = getClass().getResource('/' + className.replace('.', '/') + ".class");
    if (url == null)
        pw.println("  class not found");
    else {
        pw.println("  " + url);
        try {
            final String algorithm = "MD5";
            byte[] digest;
            MessageDigest md = MessageDigest.getInstance(algorithm);
            DigestInputStream in = new DigestInputStream(url.openStream(), md);
            try {
                byte[] buf = new byte[8192];
                int n;
                do { n = in.read(buf); } while (n > 0);
                digest = md.digest();
            } finally {
                in.close();
            }
            StringBuilder sb = new StringBuilder();
            for (byte b: digest)
                sb.append(String.format("%02x", b));
            pw.println("  " + algorithm + " checksum: " + sb);
        } catch (Exception e) {
            pw.println("  cannot compute digest: " + e);
        }
    }
}
 
Example 18
Source File: Main.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/** Display the location and checksum of a class. */
void showClass(String className) {
    PrintWriter pw = log.getWriter(WriterKind.NOTICE);
    pw.println("javac: show class: " + className);
    URL url = getClass().getResource('/' + className.replace('.', '/') + ".class");
    if (url == null)
        pw.println("  class not found");
    else {
        pw.println("  " + url);
        try {
            final String algorithm = "MD5";
            byte[] digest;
            MessageDigest md = MessageDigest.getInstance(algorithm);
            DigestInputStream in = new DigestInputStream(url.openStream(), md);
            try {
                byte[] buf = new byte[8192];
                int n;
                do { n = in.read(buf); } while (n > 0);
                digest = md.digest();
            } finally {
                in.close();
            }
            StringBuilder sb = new StringBuilder();
            for (byte b: digest)
                sb.append(String.format("%02x", b));
            pw.println("  " + algorithm + " checksum: " + sb);
        } catch (Exception e) {
            pw.println("  cannot compute digest: " + e);
        }
    }
}
 
Example 19
Source File: AbstractGalaxySigner.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
protected byte[] hash(InputStream inputstream)
{
    byte abyte1[];
    try
    {
        DigestInputStream digestinputstream = new DigestInputStream(inputstream, MessageDigest.getInstance("SHA-256"));
        for (byte abyte0[] = new byte[1024]; digestinputstream.read(abyte0) > -1;) { }
        abyte1 = digestinputstream.getMessageDigest().digest();
    }
    catch (Exception exception)
    {
        throw new GalaxyClientException(ReturnCode.SIGNATURE_FAILED, (new StringBuilder()).append("Unable to compute hash while signing request: ").append(exception.getMessage()).toString(), exception);
    }
    return abyte1;
}
 
Example 20
Source File: Main.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/** Display the location and checksum of a class. */
void showClass(String className) {
    PrintWriter pw = log.getWriter(WriterKind.NOTICE);
    pw.println("javac: show class: " + className);
    URL url = getClass().getResource('/' + className.replace('.', '/') + ".class");
    if (url == null)
        pw.println("  class not found");
    else {
        pw.println("  " + url);
        try {
            final String algorithm = "MD5";
            byte[] digest;
            MessageDigest md = MessageDigest.getInstance(algorithm);
            DigestInputStream in = new DigestInputStream(url.openStream(), md);
            try {
                byte[] buf = new byte[8192];
                int n;
                do { n = in.read(buf); } while (n > 0);
                digest = md.digest();
            } finally {
                in.close();
            }
            StringBuilder sb = new StringBuilder();
            for (byte b: digest)
                sb.append(String.format("%02x", b));
            pw.println("  " + algorithm + " checksum: " + sb);
        } catch (Exception e) {
            pw.println("  cannot compute digest: " + e);
        }
    }
}