-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSHA256Hashing.java
33 lines (23 loc) · 1016 Bytes
/
SHA256Hashing.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.wtech.core.hashing;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
public class SHA256Hashing {
public static String hashPassword(String password) throws Exception {
// Securely generate a random salt
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
return hashPasswordWithSalt(password, salt);
}
public static String hashPasswordWithSalt(String password, byte[] salt) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(salt);
byte[] hashedPassword = md.digest(password.getBytes());
return Base64.getEncoder().encodeToString(hashedPassword);
}
public static boolean verifyPassword(String inputPassword, String storedHash, byte[] salt) throws Exception {
String newHash = hashPasswordWithSalt(inputPassword, salt);
return newHash.equals(storedHash);
}
}