thieumao

File to SHA1

Sep 15th, 2013
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package test;
  6.  
  7. import java.io.FileInputStream;
  8. import java.io.IOException;
  9. import java.security.MessageDigest;
  10. import java.security.NoSuchAlgorithmException;
  11.  
  12. public class FileToSHA1 {
  13.  
  14.     public static void main(String[] args) throws Exception {
  15.         String str = ToSHA1("D:/Coding/HashCalc.exe");
  16.         System.out.println(str);
  17.     }
  18.  
  19.     private static String ToSHA1(String FilePath) throws Exception {
  20.         MessageDigest md = MessageDigest.getInstance("SHA1");
  21.         FileInputStream fis = new FileInputStream(FilePath);
  22.         byte[] dataBytes = new byte[1024];
  23.         int nread = 0;
  24.         while ((nread = fis.read(dataBytes)) != -1) {
  25.             md.update(dataBytes, 0, nread);
  26.         };
  27.         byte[] mdbytes = md.digest();
  28.         //convert the byte to hex
  29.         StringBuffer sb = new StringBuffer();
  30.         for (int i = 0; i < mdbytes.length; i++) {
  31.             sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
  32.         }
  33.         return sb.toString();
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment