org.apache.shiro.crypto.hash.SimpleHash Java Examples

The following examples show how to use org.apache.shiro.crypto.hash.SimpleHash. 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: AdminControllerTest.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@Test
public void userInfoAdd() {
    Admin admin = new Admin();
    int hashIterations = 2;//加密的次数
    Object salt = "longyan";//盐值这里的salt是 username+salt(一般是用户名加一个随机字符串), 这里以字符串“long”为例)
    Object credentials = "123456";//密码
    String hashAlgorithmName = "MD5";//加密方式
    Object simpleHash = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
    admin.setUsername("long");
    admin.setPassword(simpleHash.toString());
    admin.setSalt("yan");
    admin.setPassword(simpleHash.toString());
    List<SysRole> roles = new ArrayList<>();
    SysRole role1 = sysRoleDao.findByRole("admin");
    roles.add(role1);
    admin.setRoleList(roles);
    adminDao.save(admin);

}
 
Example #2
Source File: AccountManager.java    From base-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 更新当前用户密码
 * 
 * @param oldPassword 旧密码
 * @param newPassword 新密码
 * 
 */
//当修改成功后将shiro的认证缓存也更新,包正下次登录也不需要在次查询数据库
@CacheEvict(value="shiroAuthenticationCache",
		  	key="T(com.github.dactiv.showcase.common.SystemVariableUtils)." +
				"getSessionVariable()." +
				"getUser()." +
				"getUsername()")
public void updateUserPassword(String oldPassword, String newPassword) {
	User user = SystemVariableUtils.getSessionVariable().getUser();
	
	oldPassword = new SimpleHash("MD5", oldPassword.toCharArray()).toString();
	
	if (!user.getPassword().equals(oldPassword)) {
		throw new ServiceException("旧密码不正确.");
	}
	
	String temp = new SimpleHash("MD5",newPassword).toHex();
	userDao.updatePassword(user.getId(),temp);
	user.setPassword(temp); 
}
 
Example #3
Source File: DefaultCredentialsSecurer.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	// String privateSalt = "IAM";
	// String privateSalt = "safecloud";
	// String privateSalt = "IamWithCipherPrivateSalt";
	String privateSalt = "iam-serverdev";
	ByteSource publicSalt = Util.bytes("admin");
	ByteSource salt = Util.bytes(crossCombined(Util.bytes(privateSalt).getBytes(), publicSalt.getBytes()));

	String[] hashAlgorithms = new String[] { "MD5", "SHA-256", "SHA-384", "SHA-512" };
	int size = hashAlgorithms.length;
	long index = crc32(salt.getBytes()) % size & (size - 1);
	String algorithm = hashAlgorithms[(int) index];
	int hashIterations = (int) (Integer.MAX_VALUE % (index + 1)) + 1;
	System.out.println(">>>>>>>>>>");
	System.out.print(new SimpleHash(algorithm, Util.bytes("123456"), salt, hashIterations).toHex());
	System.out.print("\n<<<<<<<<<<");
}
 
Example #4
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 #5
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 #6
Source File: AbstractCredentialsSecurerSupport.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
@Override
public String signature(@NotNull CredentialsToken token) {
	// Delegate signature
	if (!isNull(delegate) && !token.isSolved()) {
		// Resolving request credentials token.
		return delegate.signature(resolves(token));
	}

	// When the delegate is null, it is unresolved.
	if (!token.isSolved()) {
		token = resolves(token); // It is necessary to resolving
	}

	// Hashing signature
	return doCredentialsHash(token,
			(algorithm, source, salt, hashIters) -> new SimpleHash(algorithm, source, salt, hashIters));
}
 
Example #7
Source File: AccountManager.java    From base-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 新增用户
 * 
 * @param entity 用户实体
 */
public void insertUser(User entity) {
	if (!isUsernameUnique(entity.getUsername())) {
		throw new ServiceException("用户名已存在");
	}
	
	String password = new SimpleHash("MD5", entity.getPassword()).toHex();
	
	entity.setPassword(password);
	userDao.insert(entity);
}
 
Example #8
Source File: test.java    From mySpringBoot with Apache License 2.0 5 votes vote down vote up
public static void main(String []ages ){
    //加密方式
    String hashAlgorithmName = "md5";
    //原密码
    String credentials = "123456";
    //加密次数
    int hashIterations = 1024;
    //加密盐值,大家可以用生成字符串的方法
    String hash = "wxKYXuTPST5SG0jMQzVPsg==";
    ByteSource credentialsSalt = ByteSource.Util.bytes(hash);
    String password = new SimpleHash(hashAlgorithmName, credentials, credentialsSalt, hashIterations).toHex();
    System.out.println(password);
}
 
Example #9
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 #10
Source File: EncryptUtils.java    From parker with MIT License 5 votes vote down vote up
/**
 * Shiro的MD5加密,加密方式是对字符串salt+password进行加密
 * @param salt 盐
 * @param password 密码
 * @return
 */
public static String shiroMd5(String salt, String password){
    String algorithmName = "MD5";
    ByteSource byteSalt = ByteSource.Util.bytes(salt);
    SimpleHash simpleHash = new SimpleHash(algorithmName, password, byteSalt, DEFAULT_ITERATIONS);
    return simpleHash.toHex();
}
 
Example #11
Source File: PasswordUtil.java    From permission with MIT License 5 votes vote down vote up
/**
 * 使用盐加密密码
 * @param user
 */
public static void encryptPassword(SysUser user){
    // 随机盐
    String salt = randomNumberGenerator.nextBytes().toString();
    user.setSalt(salt);
    //将用户的注册密码经过散列算法替换成一个不可逆的新密码保存进数据,使用过程使用了盐
    String newPassword = new SimpleHash(algorithmName, user.getPassword(), salt, hashIterations).toString();
    user.setPassword(newPassword);
}
 
Example #12
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 #13
Source File: UserServiceTest.java    From White-Jotter with MIT License 5 votes vote down vote up
@Test
public void testResetPassword_Normal() {
    User testUser = User.builder()
            .username("utest").password("123456").name("测试用户").email("[email protected]").phone("12312312312").build();

    when(userDAO.findByUsername("utest")).thenReturn(testUser);
    when(userDAO.save(any(User.class))).thenAnswer(i ->  i.getArguments()[0]);

    User resetUser = userService.resetPassword(testUser);
    Assert.assertThat(resetUser.getPassword(),is(new SimpleHash("md5", "123", resetUser.getSalt(), 2).toString()));
}
 
Example #14
Source File: AccountRealm.java    From Roothub with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {
	String hashAlgorithmName = "MD5";
	Object credentials = "123";
	Object salt = ByteSource.Util.bytes("admin");
	int hashIterations = 1024;
	Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
	System.out.println(result);
}
 
Example #15
Source File: CodeUtils.java    From DouBiNovel with Apache License 2.0 5 votes vote down vote up
public static String MD5Pwd(String username, String pwd) {
    // 加密算法MD5
    // salt盐 username + salt
    // 迭代次数
    String md5Pwd = new SimpleHash("md5", pwd, ByteSource.Util.bytes(username + "salt"), 2).toHex();
    return md5Pwd;
}
 
Example #16
Source File: DefaultPasswordProvider.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public String encrypt(String plainPassord) {
	return new SimpleHash(
					this.properties.getPasswdAlg()
					,plainPassord
					,this.properties.getPasswdSalt()
					,this.properties.getPasswdIterations()
		   ).toHex();
}
 
Example #17
Source File: PasswordHelper.java    From wetech-admin with MIT License 5 votes vote down vote up
public void encryptPassword(User user) {

        user.setSalt(randomNumberGenerator.nextBytes().toHex());

        String newPassword = new SimpleHash(
                algorithmName,
                user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()),
                hashIterations).toHex();

        user.setPassword(newPassword);
    }
 
Example #18
Source File: PasswordHelper.java    From wetech-admin with MIT License 5 votes vote down vote up
public boolean verifyPassword(User user, String password) {
    String hash = new SimpleHash(
            algorithmName,
            password,
            ByteSource.Util.bytes(user.getCredentialsSalt()),
            hashIterations
    ).toHex();
    user.getPassword();
    return user.getPassword().equals(hash);
}
 
Example #19
Source File: PasswordHelper.java    From mumu with Apache License 2.0 5 votes vote down vote up
/**
 * 加密密码
 * @param realm
 */
public static BaseRealm encryptPassword(BaseRealm realm) {
	realm.setSalt(randomNumberGenerator.nextBytes().toHex());
	String credentialsSalt = realm.getUserName() + realm.getSalt();
	String newPassword = new SimpleHash(algorithmName, realm.getPassword(),
			ByteSource.Util.bytes(credentialsSalt), hashIterations).toHex();

	realm.setPassword(newPassword);
	return realm;
}
 
Example #20
Source File: MD5Util.java    From easyweb with Apache License 2.0 5 votes vote down vote up
/**
 * shiro密码
 * @param str
 * @param salt
 * @return
 */
public final static String shiroPwd(String str,String salt){
    String credentials = str;
    ByteSource credentialsSalt = ByteSource.Util.bytes(salt);
    String obj = new SimpleHash(HASH_ALGORITHM, credentials, credentialsSalt, HASH_INTERATIONS).toHex();
    return obj;
}
 
Example #21
Source File: PasswordHelper.java    From cms with Apache License 2.0 5 votes vote down vote up
public void encryptPassword(Account account) {

    	account.setSalt(randomNumberGenerator.nextBytes().toHex());

        String newPassword = new SimpleHash(
                algorithmName,
                account.getPassword(),
                ByteSource.Util.bytes(account.getCredentialsSalt()),
                hashIterations).toHex();

        account.setPassword(newPassword);
    }
 
Example #22
Source File: PasswordHelper.java    From cms with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param account 输入 name , salt, password(明文)
 * @param password 加密的
 * @return
 */
public boolean verifyPassword(Account account,String password){
	
	String newPassword = new SimpleHash(
            algorithmName,
            account.getPassword(),
            ByteSource.Util.bytes(account.getCredentialsSalt()),
            hashIterations).toHex();
	
	return newPassword.equals(password);
}
 
Example #23
Source File: WebPageSource.java    From cms with Apache License 2.0 5 votes vote down vote up
@Test
public void SimpleHash() throws NoSuchAlgorithmException {
    String salt = "5909af55d288d8f2581f7d572f2eb6bb"; //new SecureRandomNumberGenerator().nextBytes().toHex();
    String newPassword = new MySimpleHash(
            "MD5",
            "123456",
            ByteSource.Util.bytes("demo" + salt),
            2).toString();


    System.out.println(salt);
    System.out.println(newPassword);
}
 
Example #24
Source File: PasswordHelper.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public void encryptPassword(User user) {
	user.setSalt(randomNumberGenerator.nextBytes().toHex());

	String newPassword = new SimpleHash(algorithmName, user.getPassword(),
		ByteSource.Util.bytes(user.getCredentialsSalt()), hashIterations).toHex();

	user.setPassword(newPassword);
}
 
Example #25
Source File: UserController.java    From JavaWeb with Apache License 2.0 5 votes vote down vote up
@PostMapping(value="/createUser",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String createUser(HttpServletRequest request, 
		  			     HttpServletResponse response,
		  			     @RequestBody User user) {
	JSONObject jo = new JSONObject();
	try{
		Result result = FluentValidator.checkAll()
					       .on(user, new HibernateSupportedValidator<User>().setHiberanteValidator(Validation.buildDefaultValidatorFactory().getValidator()))//常规校验
                   				       .on(user.getUsername(), new UsernameValidator())//特殊校验
                   				       //.on(user.getUsername(), new UsernameValidator())
                   				       .doValidate()
                   				       .result(ResultCollectors.toSimple());
		if(result.isSuccess()){
			user.setUserid(GenerateUtil.getRandomUUID());
			user.setPassword(new SimpleHash("SHA-1", user.getUsername(), user.getPassword()).toString());
			userService.createUser(user);
			jo.put("message", "新建用户成功");
		}else{
			jo.put("message", result.getErrors().get(0));
		}
	}catch(Exception e){
		jo.put("message", "新建用户失败");
	}
	//System.out.println(jo.toString());
	return jo.toString();
}
 
Example #26
Source File: PasswordHelper.java    From VideoMeeting with Apache License 2.0 5 votes vote down vote up
public void encryptPassword(User user) {
	// 加密方式要和配置文件中配置的方式相一致
	user.setSalt(randomNumberGenerator.nextBytes().toHex());
	String newPassword = new SimpleHash(algorithmName, user.getPassword(),
			ByteSource.Util.bytes(user.getCredentialsSalt()),
			hashIterations).toHex();
	user.setPassword(newPassword);
}
 
Example #27
Source File: ShiroPasswordService.java    From EasyReport with Apache License 2.0 5 votes vote down vote up
@Override
public String encode(final CharSequence rawPassword, final String credentialsSalt) {
    return new SimpleHash(
        this.algorithmName,
        rawPassword,
        ByteSource.Util.bytes(credentialsSalt),
        this.hashIterations).toHex();
}
 
Example #28
Source File: AdminController.java    From Spring-Boot-Book with Apache License 2.0 5 votes vote down vote up
/**
  * 用户添加
  */
 @RequestMapping("/addtest")
 /**
  * 权限管理
  */
@RequiresPermissions("admin:add")
 public String adminAdd(String name, String password, String role) {
     Admin admin = new Admin();
     /**
      * 加密的次数
      */
     int hashIterations = 2;
     /**
      * 盐值这里的salt是 username+salt(一般是用户名加一个随机字符串), 这里以字符串“long”为例)
      */
     Object salt = "longyan";
     /**
      * 密码
      */
     Object credentials = "123456";
     /**
      * 加密方式
      */
     String hashAlgorithmName = "MD5";
     Object simpleHash = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
     admin.setUsername("long2");
     admin.setPassword(simpleHash.toString());
     admin.setSalt("yan");
     admin.setPassword(simpleHash.toString());
     List<SysRole> roles = new ArrayList<>();
     SysRole role1 = sysRoleDao.findByRole("admin");
     roles.add(role1);
     admin.setRoleList(roles);
     adminDao.save(admin);
     return "Add";
 }
 
Example #29
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 #30
Source File: PasswordUtil.java    From permission with MIT License 4 votes vote down vote up
public static String encryptPassword(String password, String salt){
    //将用户的注册密码经过散列算法替换成一个不可逆的新密码保存进数据,使用过程使用了盐
    String newPassword = new SimpleHash(algorithmName, password, salt, hashIterations).toString();
    return newPassword;
}