Created
July 1, 2015 23:53
-
-
Save drguildo/3116a0a4ea0618fe7146 to your computer and use it in GitHub Desktop.
A quick little utility to generate SHA-256 file hashes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.sjm.hash; | |
import java.io.BufferedInputStream; | |
import java.io.BufferedWriter; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.math.BigInteger; | |
import java.security.MessageDigest; | |
import java.util.Arrays; | |
public class Main { | |
public static String calc(InputStream is) { | |
String output; | |
int read; | |
byte[] buffer = new byte[8192]; | |
try { | |
MessageDigest digest = MessageDigest.getInstance("SHA-256"); | |
while ((read = is.read(buffer)) > 0) { | |
digest.update(buffer, 0, read); | |
} | |
byte[] hash = digest.digest(); | |
BigInteger bigInt = new BigInteger(1, hash); | |
output = bigInt.toString(16); | |
while (output.length() < 64) { | |
output = "0" + output; | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return null; | |
} | |
return output; | |
} | |
public static String calcFile(String filename) { | |
String format = "SHA256 (%s) = %s"; | |
File f = new File(filename); | |
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f))) { | |
return String.format(format, f.getName(), calc(bis)); | |
} catch (IOException e) { | |
System.err.println(e.getClass() + ": " + e.getMessage()); | |
} | |
return null; | |
} | |
public static void main(String[] args) { | |
String[] opts = args.clone(); | |
if (opts.length == 0) { | |
System.err.println("usage: hash.jar [-w] <filename>\n"); | |
System.err.println("-w:\twrite the output to \"SHA256\""); | |
System.exit(-1); | |
} | |
boolean writeFile = false; | |
if (opts[0].equals("-w")) { | |
File f = new File("SHA256"); | |
if (f.exists()) { | |
System.err.println("File " + f.getName() + " already exists."); | |
System.exit(-1); | |
} | |
writeFile = true; | |
opts = Arrays.copyOfRange(opts, 1, opts.length); | |
} | |
StringBuffer sb = new StringBuffer(); | |
Arrays.stream(opts).forEach(opt -> sb.append(calcFile(opt) + "\n")); | |
if (writeFile) { | |
File f = new File("SHA256"); | |
try (BufferedWriter bw = new BufferedWriter(new FileWriter(f))) { | |
bw.write(sb.toString()); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} else { | |
System.out.print(sb); | |
} | |
System.exit(0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment