微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我在申请认证时使用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);
}

我在我的数据库中使用String存储salt.现在在我的领域我想从数据库获取我的数据,我使用了一个transactionnal服务.但是我的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已经为每个密码生成了唯一的salt.

但是,不需要实现自定义PasswordService来向每个用户的salt添加私有盐(有时称为“pepper”).私有盐可以在shiro.ini中配置:

[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=

私有盐不存储在数据库中,如果攻击者获得对数据库转储的访问权限,则很难破解密码.

此示例是使用shiro-1.2.2创建的

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

原文地址:https://www.jb51.cc/mssql/79465.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐