|
| 1 | +import java.nio.charset.StandardCharsets; |
| 2 | +import java.security.MessageDigest; |
| 3 | +import java.security.NoSuchAlgorithmException; |
| 4 | + |
| 5 | +public class SHAHash { |
| 6 | + |
| 7 | + /** |
| 8 | + * It is the same domain as the class 'SHAHash.java' from the app. |
| 9 | + */ |
| 10 | + public static final String DOMAIN = "com.aristy.gogocar"; |
| 11 | + |
| 12 | + /** |
| 13 | + * Main method |
| 14 | + * @param args |
| 15 | + */ |
| 16 | + public static void main(String[] args){ |
| 17 | + if (args.length < 1) { |
| 18 | + System.out.println("Need an argument. abord. "); |
| 19 | + System.out.println("Try 'cat --help' for more information."); |
| 20 | + return; |
| 21 | + } |
| 22 | + if (args.length > 2){ |
| 23 | + System.out.println("Too many arguments. abord. "); |
| 24 | + System.out.println("Try 'cat --help' for more information."); |
| 25 | + return; |
| 26 | + } |
| 27 | + if (args[0].equals("--help") || args[0].equals("-h")){ |
| 28 | + System.out.println("Usage: java SHAHash [TEXT] [DOMAIN]"); |
| 29 | + System.out.println("Hash TEXT using SHA-512.\n"); |
| 30 | + System.out.println("-h, --help display this help and exit.\n"); |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + String domain = (args.length == 1) ? DOMAIN : args[1]; |
| 35 | + String hash = hashPassword(args[0], domain); |
| 36 | + |
| 37 | + System.out.println("Hashed text: " + hash + " , len " + hash.length()); |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Hash a text using SHA-512 |
| 42 | + * @param password text |
| 43 | + * @param domain domain or salt |
| 44 | + * @return thje hash |
| 45 | + */ |
| 46 | + public static String hashPassword(String password, String domain) { |
| 47 | + String pw = password + domain; |
| 48 | + MessageDigest sha; |
| 49 | + byte[] byteData; |
| 50 | + try { |
| 51 | + sha = MessageDigest.getInstance("SHA-512"); |
| 52 | + byteData = sha.digest(pw.getBytes(StandardCharsets.UTF_8)); |
| 53 | + return convertHex(byteData); |
| 54 | + } catch (NoSuchAlgorithmException e) { |
| 55 | + e.printStackTrace(); |
| 56 | + return ""; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * Convert byte array to String |
| 62 | + * @param byteData bytes |
| 63 | + * @return String |
| 64 | + */ |
| 65 | + private static String convertHex(byte[] byteData){ |
| 66 | + StringBuilder hexString = new StringBuilder(); |
| 67 | + for (byte byteDatum : byteData) { |
| 68 | + String hex = Integer.toHexString(0xff & byteDatum); |
| 69 | + if (hex.length() == 1) hexString.append('0'); |
| 70 | + hexString.append(hex); |
| 71 | + } |
| 72 | + return hexString.toString(); |
| 73 | + } |
| 74 | + |
| 75 | + |
| 76 | +} |
0 commit comments