gpt4 book ai didi

java - 如何从数据库中储存和使用 shiro 盐

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:30:01 26 4
gpt4 key购买 nike

我在申请中使用 shiro 进行身份验证。我使用加盐的散列密码,并将它们存储在我的数据库中,如下所示:

    private User createUserWithHashedPassword(String inName, String inFirstName, String inLastName, String inPassword){

ByteSource salt = randomNumberGenerator.nextBytes(32);

byte[] byteTabSalt = salt.getBytes();

String strSalt = byteArrayToHexString(byteTabSalt);

String hashedPasswordBase64 = new Sha256Hash(inPassword, salt, 1024).toBase64();

return new User(inName,inFirstName,inLastName,hashedPasswordBase64,strSalt);
}

我在我的数据库中用字符串存储盐。现在在我的领域中,我想从数据库中取回我的数据,为此我使用了事务服务。但是我的 salt 是 Strong 所以我希望它通过静态方法返回为 ByteSource 类型:

ByteSource byteSourceSalt = Util.bytes(salt); //where the salt is a String

但是当我创建我的 SaltedAuthenticationInfo 时它不授权。

我认为我的问题出在我的转换方法上:

private String byteArrayToHexString(byte[] bArray){

StringBuffer buffer = new StringBuffer();

for(byte b : bArray) {
buffer.append(Integer.toHexString(b));
buffer.append(" ");
}

return buffer.toString().toUpperCase();
}

感谢您的帮助。

最佳答案

如优秀答案中所述https://stackoverflow.com/a/20206115/603901 , Shiro 的 DefaultPasswordService 已经为每个密码生成唯一的盐。

但是,无需实现自定义 PasswordService 即可将私有(private)盐(有时称为“胡椒”)添加到每个用户的盐中。可以在shiro.ini中配置私有(private)盐:

[main]
hashService = org.apache.shiro.crypto.hash.DefaultHashService
hashService.hashIterations = 500000
hashService.hashAlgorithmName = SHA-256
hashService.generatePublicSalt = true
# privateSalt needs to be base64-encoded in shiro.ini but not in the Java code
hashService.privateSalt = myVERYSECRETBase64EncodedSalt
passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher

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

用于生成匹配密码哈希的 Java 代码:

DefaultHashService hashService = new DefaultHashService();
hashService.setHashIterations(HASH_ITERATIONS); // 500000
hashService.setHashAlgorithmName(Sha256Hash.ALGORITHM_NAME);
hashService.setPrivateSalt(new SimpleByteSource(PRIVATE_SALT)); // Same salt as in shiro.ini, but NOT base64-encoded.
hashService.setGeneratePublicSalt(true);

DefaultPasswordService passwordService = new DefaultPasswordService();
passwordService.setHashService(hashService);
String encryptedPassword = passwordService.encryptPassword("PasswordForThisUser");

生成的散列如下所示:

$shiro1$SHA-256$500000$An4HRyqMJlZ58utACtyGDQ==$nKbIY9Nd9vC89G4SjdnDfka49mZiesjWgDsO/4Ly4Qs=

私有(private)盐不存储在数据库中,这使得如果对手获得对数据库转储的访问权限,则更难破解密码。

这个例子是使用shiro-1.2.2创建的

感谢https://github.com/Multifarious/shiro-jdbi-realm/blob/master/src/test/resources/shiro.ini寻求 shiro.ini 语法方面的帮助

关于java - 如何从数据库中储存和使用 shiro 盐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12496600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com