I have built a custom realm using Apache Shiro to account for our application having more than one location for user accounts and stored passwords. Originally I was using Shiro to hash and match the passwords, but the custom realm means I have to do some of these things manually.
After looking I came across this code:
public String sha256(String base) {
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(base.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
}
I added a salt and it works great, so I'm wondering if I can just store the returned value in a database when creating a username\password pair and then later retrieve it to match the provided password (plus the salt). That seems like it should work, but when I did this previously with Shiro the SHA256 password hasher did NOT return the same value with the same base password each time, yet it was able to always match it. I wanted to make sure I'm following a valid (and most importantly secure) methodology for handling passwords.
A couple things:
You can create a hash of a string buy using something like: new Sha256Hash(password, salt)
Take a look at this example
If you have multiple places your users are stored, you should probably have a different realm for each store .