Advertisement
Guest User

Untitled

a guest
Feb 19th, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. import java.io.*;
  2. import java.nio.file.*;
  3.  
  4. import java.util.Scanner;
  5. import java.security.MessageDigest;
  6. import java.security.NoSuchAlgorithmException;
  7.  
  8. public class SHA256Sum {
  9. public static void main(String[] args) {
  10. if (args.length == 0) {
  11. try {
  12. printSHA256SystemIn();
  13. } catch (NoSuchAlgorithmException e) {
  14. System.err.println("ERROR: cannot find SHA-256 algorithm.");
  15. return;
  16. }
  17. } else {
  18. for (String filePath : args) {
  19. try {
  20. printSHA256(filePath);
  21. } catch (NoSuchAlgorithmException e) {
  22. System.err.println("ERROR: cannot find SHA-256 algorithm.");
  23. return;
  24. } catch (FileNotFoundException e) {
  25. System.err.println("ERROR: " + filePath + ": file not found.");
  26. return;
  27. } catch (IOException e) {
  28. System.err.println("ERROR: " + filePath + ": cannot read from file.");
  29. return;
  30. }
  31. }
  32. }
  33. }
  34.  
  35. public static void printSHA256(String filePath) throws NoSuchAlgorithmException, IOException {
  36. MessageDigest md = MessageDigest.getInstance("SHA-256");
  37. md.update(Files.readAllBytes(Paths.get(filePath)));
  38.  
  39. for (byte b : md.digest()) {
  40. System.out.print(String.format("%02x", b).toUpperCase());
  41. }
  42.  
  43. System.out.println(" *" + filePath);
  44. }
  45.  
  46. public static void printSHA256SystemIn() throws NoSuchAlgorithmException {
  47. MessageDigest md = MessageDigest.getInstance("SHA-256");
  48. Scanner input = new Scanner(System.in);
  49.  
  50. while (input.hasNextLine()) {
  51. md.update(input.nextLine().getBytes());
  52. }
  53.  
  54. for (byte b : md.digest()) {
  55. System.out.print(String.format("%02x", b).toUpperCase());
  56. }
  57.  
  58. System.out.println(" *-");
  59. input.close();
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement