java_passwords/saltedHash.java

56 lines
1.8 KiB
Java
Raw Permalink Normal View History

2023-10-23 18:17:38 +11:00
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class saltedHash {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string to hash and salt: ");
String input = reader.readLine();
try {
String salt = bytetohex.toHexString(getSalt());
// Remove starting 0s
while (salt.charAt(0) == '0') {
salt = salt.substring(1);
}
String salted = input + salt;
2023-10-25 13:48:43 +11:00
System.out.println("Stored as:");
2023-10-23 18:17:38 +11:00
String hashed = hash.hashstring(salted);
2023-10-23 18:50:45 +11:00
String stored = hashed + "$"+salt;
2023-10-23 18:17:38 +11:00
System.out.println(stored);
System.out.println("Enter a string to check: ");
String check = reader.readLine();
// Split stored by the colon
2023-10-23 18:50:45 +11:00
String[] parts = stored.split("\\$");
2023-10-23 18:17:38 +11:00
// Salt the checked
String saltedCheck = check + parts[1];
// Hash the salted checked
String hashedCheck = hash.hashstring(saltedCheck);
// Compare the hashed salted checked to the stored hash
if (hashedCheck.equals(parts[0])) {
System.out.println("Match!");
} else {
System.out.println("No match!");
}
} catch (NoSuchAlgorithmException e) {
System.out.println(e.toString());
}
}
2023-10-23 18:50:45 +11:00
public static byte[] getSalt() throws NoSuchAlgorithmException {
2023-10-23 18:17:38 +11:00
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
return salt;
}
}