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;
- //using SHA to hash string
- public class HashSHA {
- public String hash(String data,String hashAlgorithm){
- String hashed="";
- try {
- MessageDigest sha = MessageDigest.getInstance(hashAlgorithm);
- sha.update(data.getBytes());
- byte byteData []=sha.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;
- }
- //using SHA to hash file
- public String hashFile(String file, String hashAlgorithm){
- String hashed = "";
- try {
- MessageDigest sha=MessageDigest.getInstance(hashAlgorithm);
- FileInputStream fs =new FileInputStream(file);
- byte [] dataBytes=new byte [1024];
- int nread=0;
- while((nread=fs.read(dataBytes))!=-1){
- sha.update(dataBytes,0,nread);
- }
- byte[] mdbytes=sha.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;
- }
- public static void main(String[] args) {
- //using HashSHA method to hash string
- HashSHA sha = new HashSHA();
- String msg = "Selamat datang di JAVA Message Digest";
- System.out.println("Message: "+msg);
- String hashed = sha.hash(msg,"SHA-1");
- System.out.println("Hash SHA-1: "+hashed);
- hashed=sha.hash(msg,"SHA-256");
- System.out.println("Hash SHA-256: "+hashed);
- hashed=sha.hash(msg,"SHA-512");
- System.out.println("Hash SHA-512: "+hashed);
- //using hashFile method to hash file
- HashSHA sha2=new HashSHA();
- String file = "C:/Users/Suwandaru/Downloads/Schedule IT RSC Project 2014 141124.xlsx";
- System.out.println("File hashing: "+file);
- String fileHashed=sha2.hashFile(file,"SHA-1");
- System.out.println("Hash SHA-1: "+fileHashed);
- fileHashed=sha2.hashFile(file,"SHA-256");
- System.out.println("Hash SHA-256: "+fileHashed);
- fileHashed=sha2.hashFile(file,"SHA-512");
- System.out.println("Hash SHA-512: "+fileHashed);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement