如何指定要在 Apache Shiro 中使用的哈希迭代次数?

How do I specify number of Hash iterations to be used in Apache Shiro?

我正在使用一个 JSF2 应用程序,我想在其中使用 Apache Shiro。虽然我不知道如何指定要使用的 Hash 迭代次数,但我已经准备好了-运行。

shiro.ini

[main]

user = com.nivis.filter.FacesAjaxAwareUserFilter    
shiro.loginUrl = /faces/login.xhtml    
user.loginUrl = /faces/login.xhtml

jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true    
jdbcRealm.authenticationQuery = SELECT password FROM app_user WHERE username = ?  

dataSource = org.apache.shiro.jndi.JndiObjectFactory       
dataSource.requiredType = javax.sql.DataSource      
dataSource.resourceName = JNDImysql  

jdbcRealm.dataSource = $dataSource      
securityManager.realms = $jdbcRealm

passwordService = org.apache.shiro.authc.credential.DefaultPasswordService    
passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher    
passwordMatcher.passwordService = $passwordService

jdbcRealm.credentialsMatcher = $passwordMatcher

[urls]  

/faces/login.xhtml = user      
/faces/index.xhtml = user      
/faces/app/** = user  

即使我没有明确指定 hash service,它确实可以对密码进行哈希处理。我看到一个例子使用:

hashService = org.apache.shiro.crypto.hash.DefaultHashService
hashService.hashIterations = 10000
hashService.hashAlgorithmName = SHA-256
passwordService.hashService = $hashService

我尝试使用它,尽管它没有任何区别。由于仅使用 PasswordService 来对密码进行哈希处理似乎就足够了,我想知道是否有一种方法可以指定要使用多少次哈希迭代?

你可以尝试这样做:

# Configure Data Source --> see web.xml for full configuration
dataSource = org.apache.shiro.jndi.JndiObjectFactory
dataSource.resourceName = <resource name>
dataSource.resourceRef = true

# Create JDBC-Realm to connect to the Datasource and set the authenticationQuery
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.dataSource = $dataSource
jdbcRealm.authenticationQuery = SELECT password FROM <user table> WHERE email = ?

# Configure JDBC realm password hashing.
hashService = org.apache.shiro.crypto.hash.DefaultHashService
hashService.hashIterations = <number of iterations>
hashService.hashAlgorithmName = SHA-256
hashService.generatePublicSalt = true
# privateSalt needs to be base64-encoded in shiro.ini but not in the Java code!
hashService.privateSalt = <base64-encoded Salt string>
passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher

passwordService = org.apache.shiro.authc.credential.DefaultPasswordService
passwordService.hashService = $hashService
passwordMatcher.passwordService = $passwordService

jdbcRealm.credentialsMatcher = $passwordMatcher

注意:这个例子也使用了私有盐。为了增加对使用彩虹表/暴力攻击计算密码的更多安全性,我强烈建议使用盐。上面的示例代码可能不是处理加盐的最佳方式,但它工作正常。还要注意盐需要在 shiro.ini 中进行 base64 编码,而不是在 java 代码中。