Hi guys,
I tried to get each line of the text file and convert it to SHA-1 formart then to binary but i could not get the output when i tried to do system.out.println
the code:
package hash;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.io.*;
import java.security.DigestInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/*Never give up on yourself Anthony*/
public class Hash {
public static void main(String[] args) throws Exception{
//open the file
FileInputStream fstream = new FileInputStream("C://Users//NTU//Desktop//hash.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
try {
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
System.out.println(calculateHash(sha1,strLine));
//System.out.println(strLine);
}
//Close the input stream
in.close();
}
catch(IOException e) {
}
}
public static String calculateHash(MessageDigest algorithm, String file) throws Exception {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DigestInputStream dis = new DigestInputStream(bis, algorithm);
while(dis.read() != -1);
byte[] hash = algorithm.digest();
return byteArray2binary(hash);
}
private static String byteArray2binary(byte[] hash) {
StringBuilder binary = new StringBuilder();
for(byte b : hash) {
int val = b;
for(int i = 0; i < 8; i++) {
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append("");
}
return binary.toString();
}
}