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

时间:2015-10-01 13:23:02

标签: hash 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来获取密码哈希值,我想知道是否有一种方法可以指定要使用多少哈希迭代?

1 个答案:

答案 0 :(得分:3)

您可以尝试这样做:

# 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

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