org.apache.shiro.crypto.SecureRandomNumberGenerator Java Examples

The following examples show how to use org.apache.shiro.crypto.SecureRandomNumberGenerator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Helpers.java    From jqm with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new user if does not exist. If it exists, it is unlocked and roles are reset (password is untouched).
 *
 * @param cnx
 * @param login
 * @param password
 *                        the raw password. it will be hashed.
 * @param description
 * @param roles
 */
static void createUserIfMissing(DbConn cnx, String login, String password, String description, String... roles)
{
    try
    {
        int userId = cnx.runSelectSingle("user_select_id_by_key", Integer.class, login);
        cnx.runUpdate("user_update_enable_by_id", userId);
        RUser.set_roles(cnx, userId, roles);
    }
    catch (NoResultException e)
    {
        String saltS = null;
        String hash = null;
        if (null != password && !"".equals(password))
        {
            ByteSource salt = new SecureRandomNumberGenerator().nextBytes();
            hash = new Sha512Hash(password, salt, 100000).toHex();
            saltS = salt.toHex();
        }

        RUser.create(cnx, login, hash, saltS, roles);
    }
}
 
Example #2
Source File: UserServiceImpl.java    From songjhh_blog with Apache License 2.0 6 votes vote down vote up
@Override
public void insertUser(UserCustom userCustom) {
    String algorithmName = "md5";
    String username = userCustom.getUsername();
    String password = userCustom.getPassword();
    String salt1 = username;
    String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();
    int hashIterations = 3;
    SimpleHash hash = new SimpleHash(algorithmName, password,
            salt1 + salt2, hashIterations);
    String encodedPassword = hash.toHex();
    userCustom.setSalt(salt2);
    userCustom.setPassword(encodedPassword);
    userCustom.setCreatetime(new Date());
    userMapper.insertSelective(userCustom);
}
 
Example #3
Source File: UserController.java    From zhcc-server with Apache License 2.0 6 votes vote down vote up
@PutMapping("/me")
public ResponseEntity<Integer> updateCurrentUser(@RequestHeader(value="X-Token") String token, @RequestBody UserDetailVO userDetail) {
    String currentUserId = this.getSubjectFromJwt(jwtUtils, token, "userId");
    UserDTO dto = new UserDTO();
    dto.setId(Integer.parseInt(currentUserId));
    dto.setName(userDetail.getName());
    dto.setLoginName(userDetail.getLoginName());
    if(!StringUtils.isBlank(userDetail.getPassword())) {
        // 随机生成salt
        SecureRandomNumberGenerator secureRandomNumberGenerator = new SecureRandomNumberGenerator();
        String salt = secureRandomNumberGenerator.nextBytes().toHex();
        
        // Md5密码
        Md5Hash md5 = new Md5Hash(userDetail.getPassword(), salt, 6);
        String md5Password = md5.toHex();
        dto.setSalt(salt);
        dto.setPassword(md5Password);
    }
    int rows = this.userService.updateCurrentUser(dto);
    return rows > 0 ? ResponseEntity.status(HttpStatus.CREATED).body(rows) :
        ResponseEntity.notFound().build();
}
 
Example #4
Source File: UserController.java    From zhcc-server with Apache License 2.0 6 votes vote down vote up
@PutMapping("/{id}/password")
public ResponseEntity<Integer> changePassword(@PathVariable("id") int userId, String password) {
    // 随机生成salt
    SecureRandomNumberGenerator secureRandomNumberGenerator = new SecureRandomNumberGenerator();
    String salt = secureRandomNumberGenerator.nextBytes().toHex();
    
    // Md5密码
    Md5Hash md5 = new Md5Hash(password, salt, 6);
    String md5Password = md5.toHex();
    
    int rows = userService.changePassword(userId, salt, md5Password);
    if(rows > 0) {
        return ResponseEntity.status(HttpStatus.CREATED).body(rows);
    }
    return ResponseEntity.notFound().build();
}
 
Example #5
Source File: UserController.java    From zhcc-server with Apache License 2.0 6 votes vote down vote up
@PostMapping("")
public ResponseEntity<UserDetailVO> saveUser(@RequestBody UserDetailVO vo, @RequestHeader(value="X-Token") String token) {
    String currentUserId = this.getSubjectFromJwt(jwtUtils, token, "userId");

    UserDTO dto = new UserDTO();
    dto.setName(vo.getName());
    dto.setLoginName(vo.getLoginName());
    dto.setCreatorId(Integer.parseInt(currentUserId));
    dto.setRoleIds(vo.getRoleIds());

    // 随机生成salt
    SecureRandomNumberGenerator secureRandomNumberGenerator = new SecureRandomNumberGenerator();
    String salt = secureRandomNumberGenerator.nextBytes().toHex();
    Md5Hash md5 = new Md5Hash(vo.getPassword(), salt, 6);
    // 设置盐
    dto.setSalt(salt);
    // 设置新密码
    String md5Password = md5.toHex();
    dto.setPassword(md5Password);

    UserDTO user = userService.saveUser(dto);
    vo.setId(user.getId());
    return ResponseEntity.status(HttpStatus.CREATED).body(vo);
}
 
Example #6
Source File: UserController.java    From jboot-admin with Apache License 2.0 6 votes vote down vote up
/**
 * 修改密码提交
 */
@Before( {POST.class, ChangePwdValidator.class} )
public void postChangepwd() {
    User sysUser = getBean(User.class, "user");
    if (!sysUser.getId().equals(AuthUtils.getLoginUser().getId())) {
        throw new BusinessException("无权操作");
    }

    String pwd = getPara("newPwd");


    String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();
    SimpleHash hash = new SimpleHash("md5", pwd, salt2, 2);
    pwd = hash.toHex();
    sysUser.setPwd(pwd);
    sysUser.setSalt2(salt2);
    sysUser.setLastUpdAcct(AuthUtils.getLoginUser().getName());
    sysUser.setLastUpdTime(new Date());
    sysUser.setNote("用户修改密码");

    if (!userService.update(sysUser)) {
        throw new BusinessException("修改密码失败");
    }

    renderJson(RestResult.buildSuccess());
}
 
Example #7
Source File: UserService.java    From White-Jotter with MIT License 5 votes vote down vote up
public int register(User user) {
    String username = user.getUsername();
    String name = user.getName();
    String phone = user.getPhone();
    String email = user.getEmail();
    String password = user.getPassword();

    username = HtmlUtils.htmlEscape(username);
    user.setUsername(username);
    name = HtmlUtils.htmlEscape(name);
    user.setName(name);
    phone = HtmlUtils.htmlEscape(phone);
    user.setPhone(phone);
    email = HtmlUtils.htmlEscape(email);
    user.setEmail(email);
    user.setEnabled(true);

    if (username.equals("") || password.equals("")) {
        return 0;
    }

    boolean exist = isExist(username);

    if (exist) {
        return 2;
    }

    // 默认生成 16 位盐
    String salt = new SecureRandomNumberGenerator().nextBytes().toString();
    int times = 2;
    String encodedPassword = new SimpleHash("md5", password, salt, times).toString();

    user.setSalt(salt);
    user.setPassword(encodedPassword);

    userDAO.save(user);

    return 1;
}
 
Example #8
Source File: UserService.java    From White-Jotter with MIT License 5 votes vote down vote up
public User resetPassword(User user) {
    User userInDB = userDAO.findByUsername(user.getUsername());
    String salt = new SecureRandomNumberGenerator().nextBytes().toString();
    int times = 2;
    userInDB.setSalt(salt);
    String encodedPassword = new SimpleHash("md5", "123", salt, times).toString();
    userInDB.setPassword(encodedPassword);
    return userDAO.save(userInDB);
}
 
Example #9
Source File: User.java    From v-mock with MIT License 5 votes vote down vote up
/**
 * 生成随机盐
 */
public void randomSalt() {
    SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
    // 一个Byte占两个字节,此处生成的3字节,字符串长度为6
    String hex = secureRandom.nextBytes(3).toHex();
    setSalt(hex);
}
 
Example #10
Source File: ShiroUtils.java    From supplierShop with MIT License 5 votes vote down vote up
/**
 * 生成随机盐
 */
public static String randomSalt()
{
    // 一个Byte占两个字节,此处生成的3字节,字符串长度为6
    SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
    String hex = secureRandom.nextBytes(3).toHex();
    return hex;
}
 
Example #11
Source File: UserServiceImpl.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
/**
 * 重置密码
 *
 * @param user
 * @return
 */
@Override
public int resetUserPwd(User user) {
    RandomNumberGenerator rng = new SecureRandomNumberGenerator();
    String salt = rng.nextBytes().toBase64();
    user.setSalt(salt);
    String hashedPasswordBase64 = new Sha256Hash(user.getPassword(), salt, 1024).toBase64();
    user.setPassword(hashedPasswordBase64);
    user.setUpdateTime(new Date());
    return dao().updateIgnoreNull(user);
}
 
Example #12
Source File: UserServiceImpl.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
/**
 * 新增
 *
 * @param user
 * @return
 */
@Override
public User insert(User user) {
    RandomNumberGenerator rng = new SecureRandomNumberGenerator();
    //密码设置
    String salt = rng.nextBytes().toBase64();
    user.setSalt(salt);
    String hashedPasswordBase64 = new Sha256Hash(user.getPassword(), salt, 1024).toBase64();
    user.setPassword(hashedPasswordBase64);

    dao().insert(user);
    this.updataRelation(user);
    return user;
}
 
Example #13
Source File: ShiroUtils.java    From ruoyiplus with MIT License 5 votes vote down vote up
/**
 * 生成随机盐
 */
public static String randomSalt()
{
    // 一个Byte占两个字节,此处生成的3字节,字符串长度为6
    SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
    String hex = secureRandom.nextBytes(3).toHex();
    return hex;
}
 
Example #14
Source File: CreationTools.java    From jqm with Apache License 2.0 5 votes vote down vote up
public static void createUser(DbConn cnx, String login, String password, RRole... roles)
{
    ByteSource salt = new SecureRandomNumberGenerator().nextBytes();
    String[] rr = new String[roles.length];
    for (int i = 0; i < roles.length; i++)
    {
        rr[i] = roles[i].getName();
    }

    RUser.create(cnx, login, new Sha512Hash(password, salt, 100000).toHex(), salt.toHex(), rr);
}
 
Example #15
Source File: MetaService.java    From jqm with Apache License 2.0 5 votes vote down vote up
public static void changeUserPassword(DbConn cnx, int userId, String newPassword)
{
    ByteSource salt = new SecureRandomNumberGenerator().nextBytes();
    String hash = new Sha512Hash(newPassword, salt, 100000).toHex();

    QueryResult qr = cnx.runUpdate("user_update_password_by_id", hash, salt.toHex(), userId);
    if (qr.nbUpdated == 0)
    {
        throw new JqmAdminApiUserException("user with this ID does not exist");
    }
}
 
Example #16
Source File: User.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 生成随机盐
 */
public void randomSalt()
{
    // 一个Byte占两个字节,此处生成的3字节,字符串长度为6
    SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
    String hex = secureRandom.nextBytes(3).toHex();
    setSalt(hex);
}
 
Example #17
Source File: Sha256CredentialsHashingStrategy.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public ByteSource generateSalt() {
   RandomNumberGenerator rng = new SecureRandomNumberGenerator();
   return rng.nextBytes();
}
 
Example #18
Source File: UserServiceImpl.java    From jboot-admin with Apache License 2.0 4 votes vote down vote up
@Override
public boolean saveUser(User user, Long[] roles) {
    String pwd = user.getPwd();

    if (StrKit.notBlank(pwd)) {
        String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();
        SimpleHash hash = new SimpleHash("md5", pwd, salt2, 2);
        pwd = hash.toHex();
        user.setPwd(pwd);
        user.setSalt2(salt2);
    }

    user.setOnlineStatus(UserOnlineStatus.OFFLINE);
    user.setCreatedate(new Date());
    user.setLastUpdTime(new Date());
    user.setNote("保存系统用户");

    return Db.tx(new IAtom() {
        @Override
        public boolean run() throws SQLException {
            if (!user.save()) {
                return false;
            }

            if (roles != null) {
                List<UserRole> list = new ArrayList<UserRole>();
                for (Long roleId : roles) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(roleId);
                    list.add(userRole);
                }
                int[] rets = userRoleService.batchSave(list);

                for (int ret : rets) {
                    if (ret < 1) {
                        return false;
                    }
                }
            }
            return true;
        }
    });
}
 
Example #19
Source File: UserServiceImpl.java    From jboot-admin with Apache License 2.0 4 votes vote down vote up
@Override
public boolean updateUser(User user, Long[] roles) {
    String pwd = user.getPwd();
    if (StrKit.notBlank(pwd)) {
        String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();
        SimpleHash hash = new SimpleHash("md5", pwd, salt2, 2);
        pwd = hash.toHex();
        user.setPwd(pwd);
        user.setSalt2(salt2);
    } else {
        user.remove("pwd");
    }

    user.setLastUpdTime(new Date());
    user.setNote("修改系统用户");

    return Db.tx(new IAtom() {
        @Override
        public boolean run() throws SQLException {
            if (!user.update()) {
                return false;
            }

            userRoleService.deleteByUserId(user.getId());

            if (roles != null) {
                List<UserRole> list = new ArrayList<UserRole>();
                for (Long roleId : roles) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(roleId);
                    list.add(userRole);
                }

                int[] rets = userRoleService.batchSave(list);
                for (int ret : rets) {
                    if (ret < 1) {
                        return false;
                    }
                }
            }
            return true;
        }
    });
}
 
Example #20
Source File: ShiroUtils.java    From RuoYi with Apache License 2.0 4 votes vote down vote up
/**
 * 生成随机盐
 */
public static String randomSalt() {
    // 一个Byte占两个字节,此处生成的3字节,字符串长度为6
    SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
    return secureRandom.nextBytes(3).toHex();
}
 
Example #21
Source File: ShiroUtil.java    From hdw-dubbo with Apache License 2.0 2 votes vote down vote up
/**
 * 获取随机盐值
 *
 * @param length 字节长度,一个字节2位16进制数表示
 * @return
 */
public static String getRandomSalt(int length) {
    return new SecureRandomNumberGenerator().nextBytes(length).toHex();
}
 
Example #22
Source File: ShiroKit.java    From SpringBootBucket with MIT License 2 votes vote down vote up
/**
 * 获取随机盐值
 *
 * @param length 字节长度,一个字节2位16进制数表示
 * @return
 */
public static String getRandomSalt(int length) {
    return new SecureRandomNumberGenerator().nextBytes(length).toHex();
}
 
Example #23
Source File: ShiroKit.java    From SpringBootBucket with MIT License 2 votes vote down vote up
/**
 * 获取随机盐值
 *
 * @param length 字节长度,一个字节2位16进制数表示
 * @return
 */
public static String getRandomSalt(int length) {
    return new SecureRandomNumberGenerator().nextBytes(length).toHex();
}
 
Example #24
Source File: SaltUtil.java    From spring-boot-plus with Apache License 2.0 2 votes vote down vote up
/**
 * 生成32位随机盐
 *
 * @return
 */
public static String generateSalt() {
    return new SecureRandomNumberGenerator().nextBytes(16).toHex();
}