Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package javaapplication1;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- /**
- *
- * @author Suwandaru
- */
- public class HashMD5 {
- public String hash(String data){
- String hashed="";
- try{
- MessageDigest md5;
- md5=MessageDigest.getInstance("MD5");
- md5.update(data.getBytes());
- byte byteData[]=md5.digest();
- //convert byte to hex
- StringBuilder sb = new StringBuilder();
- for (int i=0;i<byteData.length;i++){
- sb.append(Integer.toString((byteData[i]&0xff)+0x100,16).substring(1));
- }
- hashed=sb.toString();
- }
- catch (NoSuchAlgorithmException e)
- {
- System.out.println(e.getMessage());
- }
- return hashed;
- }
- public String hashFile (String file) {
- String hashed = "";
- try {
- MessageDigest md=MessageDigest.getInstance("MD5");
- FileInputStream fs = new FileInputStream(file);
- byte[] dataBytes = new byte [1024];
- int nread=0;
- while ((nread=fs.read(dataBytes))!=-1){
- md.update(dataBytes,0,nread);
- }
- byte[] mdbytes=md.digest();
- //convert byte to hex
- StringBuilder sb=new StringBuilder();
- for (int i=0;i<mdbytes.length;i++){
- sb.append(Integer.toString((mdbytes[i]&0xff)+0x100,16).substring(1));
- }
- hashed=sb.toString();
- }catch (NoSuchAlgorithmException e)
- {
- System.out.println(e.getMessage());
- } catch (FileNotFoundException e){
- System.out.println(e.getMessage());
- } catch (IOException e){
- System.out.println(e.getMessage());
- }
- return hashed;
- }
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- //using hash method to hash string
- HashMD5 md5 = new HashMD5();
- String msg = "Selamat datang di Java Message Digest";
- String hashed = md5.hash(msg);
- System.out.println("Message: "+msg);
- System.out.println("Hashing: "+hashed);
- //using hashFile method to hash file
- HashMD5 md52 = new HashMD5();
- String file = "C:/Users/Suwandaru/Downloads/Schedule IT RSC Project 2014 141124.xlsx";
- String fileHashed = md52.hashFile(file);
- System.out.println("File hashing: "+file);
- System.out.println("Hashing: "+fileHashed);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement