-->

how to get/set the salt for a JdbcRealm

2019-05-16 20:52发布

问题:

I am attempting to use the Shiro JdbcRealm and SHA256 hashedcredentialsMatcher. I need to update a legacy database and assign the appropriate salt for each user (via a batch routine).

how do I get/set the salt for a given account using the Shiro framework?

回答1:

With Shiro 1.2.3 all you need to do is:

  1. Extend JdbcRealm and set salt style.

    public class JdbcSaltRealm extends JdbcRealm {
        public JdbcSaltRealm() {
            setSaltStyle(SaltStyle.COLUMN);
        }
    }
    
  2. Update shiro.ini to use extended realm and to get salt column from DB

    credentialsMatcher = org.apache.shiro.authc.credential.HashedCredentialsMatcher
    credentialsMatcher.hashAlgorithmName = SHA-256
    jdbcRealm = com.mypackage.JdbcSaltRealm
    jdbcRealm.authenticationQuery = SELECT password, salt FROM user WHERE username = ?
    jdbcRealm.credentialsMatcher = $credentialsMatcher
    
  3. Hash & salt current / new user passwords. This should be done for all existing users as well as on new user registrations.

    private void saltHashPassword(String password) {
    
        String salt = new BigInteger(250, new SecureRandom()).toString(32);
    
        //TODO: save salt value to "salt" column in user table
    
        Sha256Hash hash = new Sha256Hash(password, 
                              (new SimpleByteSource(salt)).getBytes());
        String saltedHashedPassword = hash.toHex();
    
        //TODO: save saltedHashedPassword value to "password" column in user table
    }
    

I hope my answer is clear and understandable.



回答2:

Maybe a bit late:

Have a look at this tutorial.
Meri, the guy who owns the blog, describes exactly how to create an own salted JDBC Realm.

This is also an acknowledged improvement in the community for version 1.3.0 .

Hope this helpes, have Fun!