How to stock and use a shiro's salt from database

前端 未结 4 642
余生分开走
余生分开走 2021-02-06 06:44

I use shiro in application for the authenticate. I use hashed password with a salt and I store them in my database like this :

    private User createUserWithHas         


        
4条回答
  •  星月不相逢
    2021-02-06 07:23

    As mentioned in the excellent answer https://stackoverflow.com/a/20206115/603901, Shiro's DefaultPasswordService already generates unique salts for each password.

    However, there is no need to implement a custom PasswordService to add a private salt (sometimes called "pepper") to the per-user salts. Private salt can be configured in 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 code for generating a matching password hash:

    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");
    

    The resulting hash looks like this:

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

    The private salt is not stored in the database, which makes it harder to crack the passwords if an adversary gains access to a database dump.

    This example was created using shiro-1.2.2

    Thanks to https://github.com/Multifarious/shiro-jdbi-realm/blob/master/src/test/resources/shiro.ini for help with the syntax for shiro.ini

提交回复
热议问题