Returns the checksum of a string or file, or "0" if no success. The 'method' argument must be "MD5" or "SHA-256".
(String method, boolean fromFile, String pathOrString)
| 488 | The 'method' argument must be "MD5" or "SHA-256". |
| 489 | */ |
| 490 | public static String getHash(String method, boolean fromFile, String pathOrString) { |
| 491 | method = method.toUpperCase(); |
| 492 | boolean md5 = method.contains("MD5"); |
| 493 | boolean sha_256 = method.contains("SHA-256"); |
| 494 | try { |
| 495 | MessageDigest digest = null; |
| 496 | if (md5) |
| 497 | digest = MessageDigest.getInstance("MD5"); |
| 498 | else if(sha_256) |
| 499 | digest = MessageDigest.getInstance("SHA-256"); |
| 500 | else |
| 501 | return "0"; |
| 502 | Path path = Paths.get(pathOrString); |
| 503 | byte[] encodedhash; |
| 504 | if (fromFile) |
| 505 | encodedhash = digest.digest(Files.readAllBytes(path)); |
| 506 | else |
| 507 | encodedhash = digest.digest(pathOrString.getBytes()); |
| 508 | |
| 509 | return bytesToHex(encodedhash); |
| 510 | |
| 511 | } catch (Exception e) {} |
| 512 | return "0"; |
| 513 | } |
| 514 | |
| 515 | private static String bytesToHex(byte[] hash) { |
| 516 | StringBuilder hexString = new StringBuilder(2 * hash.length); |
no test coverage detected