Example usage for org.apache.shiro.crypto SecureRandomNumberGenerator SecureRandomNumberGenerator

List of usage examples for org.apache.shiro.crypto SecureRandomNumberGenerator SecureRandomNumberGenerator

Introduction

In this page you can find the example usage for org.apache.shiro.crypto SecureRandomNumberGenerator SecureRandomNumberGenerator.

Prototype

public SecureRandomNumberGenerator() 

Source Link

Document

Creates a new instance with a default backing SecureRandom SecureRandom and a #getDefaultNextBytesSize() defaultNextBytesSize of 16 , which equals 128 bits, a size commonly used in cryptographic algorithms.

Usage

From source file:CryptoTest.java

License:Apache License

@Test
public void test_hashingService() {
    log.info("*** test_hashingService ***");
    final DefaultHashService hashService = new DefaultHashService();

    final SecureRandomNumberGenerator secureRandomNumberGenerator = new SecureRandomNumberGenerator();
    secureRandomNumberGenerator.setDefaultNextBytesSize(64);
    final ByteSource privateSalt = secureRandomNumberGenerator.nextBytes();
    final ByteSource publicSalt = secureRandomNumberGenerator.nextBytes();

    log.info("privateSalt .length = {}", privateSalt.getBytes().length);

    hashService.setHashAlgorithmName("SHA-512");
    hashService.setHashIterations(1024 * 64);
    hashService.setPrivateSalt(privateSalt);
    hashService.setRandomNumberGenerator(secureRandomNumberGenerator);
    hashService.setGeneratePublicSalt(true);

    final HashRequest hashRequest = new HashRequest.Builder().setSource("password").setSalt(publicSalt).build();
    final Hash hash = hashService.computeHash(hashRequest);
    log.info("hash.salt : {}", hash.getSalt());
    log.info("publicSalt : {}", publicSalt);
    log.info("hash Base64 : {}", hash.toBase64());
    final String hash1 = hashService.computeHash(hashRequest).toBase64();
    final String hash2 = hashService.computeHash(hashRequest).toBase64();
    log.info("hash1 Base64 : {}", hash1);
    log.info("hash2 Base64 : {}", hash2);
    Assert.assertEquals(hash1, hash2);/*from   ww w  .jav  a 2s  .  c  o  m*/

    Sha512Hash encodedPassword = new Sha512Hash("password", publicSalt, 1024 * 64);
    Sha512Hash encodedPassword2 = new Sha512Hash(encodedPassword.getBytes(), privateSalt, 1024 * 64);
    log.info("encodedPassword Base64 : {}", encodedPassword.toBase64());
    log.info("encodedPassword2 Base64 : {}", encodedPassword2.toBase64());

    Sha512Hash encodedPassword3 = new Sha512Hash("password", publicSalt, 1024 * 64);
    Sha512Hash encodedPassword4 = new Sha512Hash(encodedPassword3.getBytes(), privateSalt, 1024 * 64);
    log.info("encodedPassword3 Base64 : {}", encodedPassword3.toBase64());
    log.info("encodedPassword4 Base64 : {}", encodedPassword4.toBase64());

    Assert.assertEquals(encodedPassword2, encodedPassword4);
}

From source file:CryptoTest.java

License:Apache License

@Test
public void test_hashingService_usingRandomSalts() {
    log.info("*** test_hashingService_usingRandomSalts ***");
    final DefaultHashService hashService = new DefaultHashService();

    final SecureRandomNumberGenerator secureRandomNumberGenerator = new SecureRandomNumberGenerator();
    secureRandomNumberGenerator.setDefaultNextBytesSize(64);
    final ByteSource privateSalt = secureRandomNumberGenerator.nextBytes();

    hashService.setHashAlgorithmName("SHA-512");
    hashService.setHashIterations(1024 * 128);
    hashService.setPrivateSalt(privateSalt);
    hashService.setRandomNumberGenerator(secureRandomNumberGenerator);
    hashService.setGeneratePublicSalt(true);

    final HashRequest hashRequest = new HashRequest.Builder().setSource("password").build();
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();//from  w  ww.  ja v a  2 s .co m
    final Hash hash = hashService.computeHash(hashRequest);
    stopWatch.stop();
    final byte[] hashBytes = hash.getBytes();

    log.info("hashBytes length = {}", hashBytes.length);
    log.info("hash Base64 length = {}", hash.toBase64().length());
    log.info("hash time: {}", stopWatch.getTime());
    log.info("hash.salt : {}", hash.getSalt());
    final ByteSource salt = hash.getSalt();
    log.info("salt : {}", salt);
    log.info("hash Base64 : {}", hash.toBase64());

    final String hash1 = hashService
            .computeHash(new HashRequest.Builder().setSource("password").setSalt(salt).build()).toBase64();
    final String hash2 = hashService
            .computeHash(new HashRequest.Builder().setSource("password").setSalt(salt).build()).toBase64();
    log.info("hash1 Base64 : {}", hash1);
    log.info("hash2 Base64 : {}", hash2);
    Assert.assertEquals(hash1, hash2);

    Sha512Hash encodedPassword = new Sha512Hash("password", salt, 1024 * 64);
    Sha512Hash encodedPassword2 = new Sha512Hash(encodedPassword.getBytes(), privateSalt, 1024 * 64);
    log.info("encodedPassword Base64 : {}", encodedPassword.toBase64());
    log.info("encodedPassword2 Base64 : {}", encodedPassword2.toBase64());

    Sha512Hash encodedPassword3 = new Sha512Hash("password", salt, 1024 * 64);
    Sha512Hash encodedPassword4 = new Sha512Hash(encodedPassword3.getBytes(), privateSalt, 1024 * 64);
    log.info("encodedPassword3 Base64 : {}", encodedPassword3.toBase64());
    log.info("encodedPassword4 Base64 : {}", encodedPassword4.toBase64());

    Assert.assertEquals(encodedPassword2, encodedPassword4);

    hashService.setHashIterations(1024 * 127);

}

From source file:CryptoTest.java

License:Apache License

@Test
public void test_secureRandomNumberGenerator_nextBytesSize() {
    log.info("*** test_secureRandomNumberGenerator_nextBytesSize ***");
    final DefaultHashService hashService = new DefaultHashService();
    final SecureRandomNumberGenerator secureRandomNumberGenerator = new SecureRandomNumberGenerator();
    secureRandomNumberGenerator.setDefaultNextBytesSize(8);
    final ByteSource privateSalt = secureRandomNumberGenerator.nextBytes();
    log.info("privateSalt = {}", privateSalt);
    log.info("privateSalt byte length = {}", privateSalt.getBytes().length);

    hashService.setHashAlgorithmName("SHA-512");
    hashService.setHashIterations(1024 * 128);
    hashService.setPrivateSalt(privateSalt);
    hashService.setRandomNumberGenerator(secureRandomNumberGenerator);
    hashService.setGeneratePublicSalt(true);

    final HashRequest hashRequest = new HashRequest.Builder().setSource("password").build();
    final Hash hash = hashService.computeHash(hashRequest);

    final DefaultHashService hashService2 = new DefaultHashService();
    final SecureRandomNumberGenerator secureRandomNumberGenerator2 = new SecureRandomNumberGenerator();
    secureRandomNumberGenerator2.setDefaultNextBytesSize(16);

    hashService2.setHashAlgorithmName("SHA-512");
    hashService2.setHashIterations(1024 * 128);
    hashService2.setPrivateSalt(privateSalt);
    hashService2.setRandomNumberGenerator(secureRandomNumberGenerator2);
    hashService2.setGeneratePublicSalt(true);

    final HashRequest hashRequest2 = new HashRequest.Builder().setSource("password").setSalt(hash.getSalt())
            .build();//w  ww. ja  v a2s .  c o  m
    final Hash hash2 = hashService.computeHash(hashRequest2);

    log.info("hash = {}", hash.toBase64());
    log.info("hash2 = {}", hash2.toBase64());

    Assert.assertEquals(hash2.toBase64(), hash.toBase64());
}

From source file:annis.service.internal.AdminServiceImpl.java

License:Apache License

@POST
@Path("users/{userName}/password")
@Consumes("text/plain")
@Produces("application/xml")
public Response changePassword(String newPassword, @PathParam("userName") String userName) {
    Subject requestingUser = SecurityUtils.getSubject();
    requestingUser.checkPermission("admin:write:user");

    ANNISUserConfigurationManager confManager = getConfManager();
    ANNISUserRealm userRealm = getUserRealm();
    if (confManager != null && userRealm != null) {
        User user = confManager.getUser(userName);
        if (user == null) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }//from  w w  w . ja v a  2  s.c  o m

        Shiro1CryptFormat format = new Shiro1CryptFormat();

        SecureRandomNumberGenerator generator = new SecureRandomNumberGenerator();
        ByteSource salt = generator.nextBytes(128 / 8); // 128 bit

        Sha256Hash hash = new Sha256Hash(newPassword, salt, 1);
        user.setPasswordHash(format.format(hash));

        if (userRealm.updateUser(user)) {
            return Response.ok().entity(user).build();
        }
    }

    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Could not change password").build();
}

From source file:cn.itganhuo.app.service.impl.UserServiceImpl.java

License:Apache License

public boolean updatePasswordByAccount(User user) {
    String algorithmName = "SHA-512";
    String salt1 = user.getAccount();
    String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();
    int hashIterations = 2;
    SimpleHash hash = new SimpleHash(algorithmName, user.getPassword(), salt1.concat(salt2), hashIterations);
    user.setPassword(hash.toBase64());/*from  w  w w  .  j  a va2 s . com*/
    user.setSalt(salt2);
    return this.userDao.updatePasswordByAccount(user);
}

From source file:cn.itganhuo.app.service.impl.UserServiceImpl.java

License:Apache License

@Transactional
@Override//from  w  w w  .ja v  a2s. com
public RespMsg userRegister(User user, HttpServletRequest request, HttpServletResponse response) {
    RespMsg respMsg = new RespMsg();
    // SQLSQL
    String tmpAccount = StringEscapeUtils.escapeSql(user.getAccount());
    String tmpPassword = StringEscapeUtils.escapeSql(user.getPassword());
    user.setAccount(tmpAccount);
    user.setPassword(tmpPassword);
    // ???
    if (user.getAccount().length() < 6 || user.getAccount().length() > 20) {
        respMsg.setStatus("1000");
        respMsg.setMessage(ConfigPool.getString("respMsg.register.AccountNumberFormatNotLegitimate"));
        return respMsg;
    }
    // ????
    if (!StringUtil.ifContainsSpecialStr(user.getAccount())) {
        respMsg.setStatus("1001");
        respMsg.setMessage(ConfigPool.getString("respMsg.register.AccountNumberFormatNotLegitimate"));
        return respMsg;
    }
    // ??
    if (user.getPassword().length() < 6 || user.getPassword().length() > 32) {
        respMsg.setStatus("2000");
        respMsg.setMessage(ConfigPool.getString("respMsg.register.PasswordFormatNotLegitimate"));
        return respMsg;
    }
    // ???
    String[] s = { "`", "~", "#", "$", "%", "^", "&", "*", "(", ")", "-", "=", "+", "{", "}", "[", "]", "|",
            "\\", ";", ":", "\'", "\"", "<", ">", ",", "/" };
    if (!StringUtil.ifContainsSpecialStr(user.getPassword(), s)) {
        respMsg.setStatus("2001");
        respMsg.setMessage(ConfigPool.getString("respMsg.register.PasswordFormatNotLegitimate"));
        return respMsg;
    }
    // ??????
    if (user.getAccount().matches("[\u4e00-\u9fa5]+") || user.getPassword().matches("[\u4e00-\u9fa5]+")) {
        respMsg.setStatus("3000");
        respMsg.setMessage(ConfigPool.getString("respMsg.common.CanNotContainChineseStr"));
        return respMsg;
    }
    // ????
    User tmp_user = userDao.loadByAccount(user.getAccount());
    if (tmp_user != null) {
        respMsg.setStatus("1002");
        respMsg.setMessage(ConfigPool.getString("respMsg.login.UnknownAccount"));
        return respMsg;
    }
    // ?
    String algorithmName = "SHA-512";
    String salt1 = user.getAccount();
    String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();
    int hashIterations = 2;
    SimpleHash hash = new SimpleHash(algorithmName, user.getPassword(), salt1.concat(salt2), hashIterations);
    // ??
    user.setPassword(hash.toBase64());
    user.setSalt(salt2);
    user.setIsLock(0);
    user.setPostDate(DateUtil.getNowDateTimeStr(null));
    user.setType(1);
    // ?
    userDao.insert(user);
    HttpUtil.setCookie(response, ConstantPool.USER_ACCOUNT_COOKIE_ID, user.getAccount());
    return respMsg;
}

From source file:com.app.util.UserUtil.java

License:Open Source License

public static String generateUnsubscribeToken(String customerId) {
    RandomNumberGenerator rng = new SecureRandomNumberGenerator();

    Object salt = rng.nextBytes();

    return new Sha512Hash(customerId, salt, 1024).toBase64();
}

From source file:com.app.util.UserUtil.java

License:Open Source License

public static String updatePasswordResetToken(int userId) throws DatabaseConnectionException, SQLException {

    RandomNumberGenerator rng = new SecureRandomNumberGenerator();

    Object randomBytes = rng.nextBytes();

    String passwordResetToken = randomBytes.toString();

    _userDAO.updatePasswordResetToken(userId, passwordResetToken);

    return passwordResetToken;
}

From source file:com.app.util.UserUtil.java

License:Open Source License

private static List<String> _generatePasswordAndSalt(String plainTextPassword) {

    RandomNumberGenerator rng = new SecureRandomNumberGenerator();

    Object salt = rng.nextBytes();

    String hashedPasswordBase64 = new Sha512Hash(plainTextPassword, salt, 1024).toBase64();

    List<String> passwordAndSalt = new ArrayList<>();

    passwordAndSalt.add(hashedPasswordBase64);
    passwordAndSalt.add(salt.toString());

    return passwordAndSalt;
}

From source file:com.atsamour.habitatweave.controller.RegisterServlet.java

License:Open Source License

private void generatePassword(User user, String plainTextPassword) {
    RandomNumberGenerator rng = new SecureRandomNumberGenerator();
    Object salt = rng.nextBytes();

    // Now hash the plain-text password with the random salt and multiple
    // iterations and then Base64-encode the value (requires less space than Hex):
    String hashedPasswordBase64 = new Sha256Hash(plainTextPassword, salt, 1024).toBase64();

    user.setPassword(hashedPasswordBase64);
    user.setSalt(salt.toString());//from w ww  . jav a 2 s  .  com
}