Java Code Examples for org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder

The following examples show how to use org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder. These examples are extracted from open source projects. 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 Project: tailstreamer   Source File: TailStreamer.java    License: MIT License 6 votes vote down vote up
public static void main(String...args) {
    System.setProperty("spring.config.name", "tailstreamer");
    System.setProperty("spring.config.location", "../conf/");

    ArgumentProcessor argumentProcessor = new ArgumentProcessor();
    if (argumentProcessor.parseArguments(args) && argumentProcessor.validateArguments()) {
        OptionSet options = argumentProcessor.getOptions();
        if (options.has("h")) {
            System.out.println(getHelpText());
        } else if (options.has("v")) {
            System.out.println("TailStreamer version " + VERSION);
        } else if (options.has("encryptPassword")) {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            System.out.println(encoder.encode((String) options.nonOptionArguments().get(0)));
        } else {
            TailStreamerApplication app = new TailStreamerApplication(TailStreamer.class, argumentProcessor.getOptions());
            app.run(args);
        }
    } else {
        System.err.println(argumentProcessor.getValidationErrorMessage());
        System.out.println(getHelpText());
        System.exit(1);
    }
}
 
Example 2
Source Project: kylin   Source File: PasswordPlaceholderConfigurer.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    if (args.length != 2) {
        printUsage();
        System.exit(1);
    }

    String encryptMethod = args[0];
    String passwordTxt = args[1];
    if ("AES".equalsIgnoreCase(encryptMethod)) {
        // for encrypt password like LDAP password
        System.out.println(encryptMethod + " encrypted password is: ");
        System.out.println(EncryptUtil.encrypt(passwordTxt));
    } else if ("BCrypt".equalsIgnoreCase(encryptMethod)) {
        // for encrypt the predefined user password, like ADMIN, MODELER.
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        System.out.println(encryptMethod + " encrypted password is: ");
        System.out.println(bCryptPasswordEncoder.encode(passwordTxt));
    } else {
        printUsage();
        System.exit(1);
    }
}
 
Example 3
@Test
public void standaloneIdmEngineWithBCryptPasswordEncoder() {
    contextRunner
        .withPropertyValues("flowable.idm.password-encoder=spring_bcrypt")
        .run(context -> {
            IdmEngine idmEngine = context.getBean(IdmEngine.class);

            assertThat(context).hasSingleBean(PasswordEncoder.class);

            org.flowable.idm.api.PasswordEncoder flowablePasswordEncoder = idmEngine.getIdmEngineConfiguration().getPasswordEncoder();
            PasswordEncoder passwordEncoder = context.getBean(PasswordEncoder.class);
            assertThat(flowablePasswordEncoder)
                .isInstanceOfSatisfying(SpringEncoder.class, springEncoder -> {
                    assertThat(springEncoder.getSpringEncodingProvider()).isEqualTo(passwordEncoder);
                });
            assertThat(passwordEncoder).isInstanceOf(BCryptPasswordEncoder.class);
        });
}
 
Example 4
Source Project: mogu_blog_v2   Source File: AdminRestApi.java    License: Apache License 2.0 6 votes vote down vote up
@AuthorityVerify
@OperationLogger(value = "重置用户密码")
@ApiOperation(value = "重置用户密码", notes = "重置用户密码")
@PostMapping("/restPwd")
public String restPwd(HttpServletRequest request,
                      @ApiParam(name = "uid", value = "管理员uid", required = true) @RequestParam(name = "uid", required = false) String uid) {

    if (StringUtils.isEmpty(uid)) {
        return ResultUtil.result(SysConf.ERROR, MessageConf.PARAM_INCORRECT);
    }

    Admin admin = adminService.getById(uid);
    PasswordEncoder encoder = new BCryptPasswordEncoder();
    admin.setPassWord(encoder.encode(DEFAULE_PWD));
    admin.setUpdateTime(new Date());
    admin.updateById();

    return ResultUtil.result(SysConf.SUCCESS, MessageConf.UPDATE_SUCCESS);
}
 
Example 5
Source Project: sanshanblog   Source File: UserService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 更改密码
 * @param code
 * @param password
 * @param responseMsgVO
 */
public void changePwd(String code, String password, ResponseMsgVO responseMsgVO) {
    String username=  UserContextHandler.getUsername();


    UserDO userDO = userRepository.findByUsername(username);
    log.info("用户:{}更改密码",userDO.getUsername());
    String key = CODE_PREFIX + CodeTypeEnum.CHANGE_PWD.getValue() + userDO.getEmail();
    String value = redisTemplate.opsForValue().get(key);
    if (!StringUtils.equals(code, value)) {
        responseMsgVO.buildWithMsgAndStatus(PosCodeEnum.PARAM_ERROR, "验证码错误");
        return;
    }

    if (!checkPassWordLegal(password, responseMsgVO)){
        return;
    }

    // 更新到mongo数据库
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    WriteResult result = userRepository.changePassword(username, passwordEncoder.encode(password));
    if (result.getN() == 0) {
        responseMsgVO.buildWithMsgAndStatus(PosCodeEnum.PARAM_ERROR, "更新失败");
        return;
    }
    responseMsgVO.buildOK();
}
 
Example 6
Source Project: abixen-platform   Source File: User.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public void changeAvatar(String imageLibraryDirectory, MultipartFile avatarFile) throws IOException {
    final File currentAvatarFile = new File(imageLibraryDirectory + "/user-avatar/" + getAvatarFileName());
    if (currentAvatarFile.exists()) {
        if (!currentAvatarFile.delete()) {
            throw new FileExistsException();
        }
    }
    final PasswordEncoder encoder = new BCryptPasswordEncoder();
    final String newAvatarFileName = encoder.encode(avatarFile.getName() + new Date().getTime()).replaceAll("\"", "s").replaceAll("/", "a").replace(".", "sde");
    final File newAvatarFile = new File(imageLibraryDirectory + "/user-avatar/" + newAvatarFileName);
    final FileOutputStream out = new FileOutputStream(newAvatarFile);
    out.write(avatarFile.getBytes());
    out.close();
    setAvatarFileName(newAvatarFileName);
}
 
Example 7
Source Project: osiam   Source File: InternalAuthenticationProvider.java    License: MIT License 5 votes vote down vote up
@Autowired
public InternalAuthenticationProvider(SCIMUserProvisioning userProvisioning,
                                      ShaPasswordEncoder shaPasswordEncoder,
                                      BCryptPasswordEncoder bCryptPasswordEncoder,
                                      @Value("${osiam.tempLock.count:0}") Integer maxLoginFailures,
                                      @Value("${osiam.tempLock.timeout:0}") Integer lockTimeout) {
    this.userProvisioning = userProvisioning;
    this.shaPasswordEncoder = shaPasswordEncoder;
    this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    this.maxLoginFailures = maxLoginFailures;
    this.lockTimeout = lockTimeout;
}
 
Example 8
Source Project: java-tutorial   Source File: AuthUserService.java    License: MIT License 5 votes vote down vote up
/**
 * 注册auth User
 *
 * @param user AuthUser
 * @return string
 */
public String register(AuthUser user) {
    String username = user.getUsername();
    if (this.findByUserName(username) != null) {
        return "用户已存在";
    }
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    String rawPassword = user.getPassword();
    user.setPassword(encoder.encode(rawPassword));
    List<String> roles = new ArrayList<>();
    roles.add("ROLE_USER");
    authMapper.register(user);
    return "注册成功";
}
 
Example 9
@BeforeAll
public static void setup() {
    MonitoringHelper.initMocks();
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(10);
    UserDetailsService userDetailsService = new InMemoryUserDetailsService(encoder);
    AuthenticationService authenticationService = mock(AuthenticationService.class);
    dummyAuthenticationProvider = new DummyAuthenticationProvider(encoder, userDetailsService, authenticationService);
}
 
Example 10
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
    builder.jdbcAuthentication()
           .passwordEncoder(new BCryptPasswordEncoder())
           .dataSource(dataSource)
           .usersByUsernameQuery("select name, password, enabled from t_account where name=?")
           .authoritiesByUsernameQuery("select name, role from t_account_role where name=?");

}
 
Example 11
Source Project: mini-platform   Source File: GatewayApplicationTests.java    License: MIT License 5 votes vote down vote up
@Test
public void encodingBCrypt() {
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    //加密时使用
    String hashPassword = passwordEncoder.encode("12345");
    log.info("BCrypt HashPassword: {}", hashPassword);
}
 
Example 12
Source Project: Milkomeda   Source File: CrustAuthenticationProvider.java    License: MIT License 5 votes vote down vote up
public CrustAuthenticationProvider(CrustProperties props, BCryptPasswordEncoder passwordEncoder) {
    this.props = props;
    // 设置BCrypt密码加密器
    if (props.isUseBcrypt() && passwordEncoder != null) {
        setPasswordEncoder(passwordEncoder);
    }
}
 
Example 13
Source Project: POC   Source File: WebSecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
public WebSecurityConfig(BCryptPasswordEncoder bCryptPasswordEncoder,
		CustomizeAuthenticationSuccessHandler customizeAuthenticationSuccessHandler,
		CustomUserDetailsServiceImpl customUserDetailsServiceImpl) {
	super();
	this.bCryptPasswordEncoder = bCryptPasswordEncoder;
	this.customizeAuthenticationSuccessHandler = customizeAuthenticationSuccessHandler;
	this.customUserDetailsServiceImpl = customUserDetailsServiceImpl;
}
 
Example 14
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .jdbcAuthentication()
            .dataSource(this.dataSource)
            .passwordEncoder(new BCryptPasswordEncoder());
}
 
Example 15
@Test
void ChangePasswordSuccessfully() throws Exception {
  UserEntity testUser = new UserEntity();
  testUser.setUsername("username");
  testUser.setPassword(PasswordUtil.hash("password1"));
  testUser = userRepository.save(testUser);

  RefreshTokenEntity refreshToken = new RefreshTokenEntity();
  refreshToken.setToken(
      tokenService.generateRefreshToken(testUser.getId(), testUser.getUsername()));
  refreshToken.setUser(testUser);
  refreshTokenRepository.save(refreshToken);

  ChangePasswordCommand command =
      new ChangePasswordCommand(refreshToken.getToken(), "newPassword1");
  mvc()
      .perform(
          post("/api/user/password/change")
              .content(toJson(command))
              .contentType(MediaType.APPLICATION_JSON))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(documentPasswordChange());

  Assertions.assertTrue(
      new BCryptPasswordEncoder()
          .matches(
              "newPassword1", userRepository.findById(testUser.getId()).get().getPassword()));
}
 
Example 16
Source Project: runscore   Source File: UserAccountService.java    License: Apache License 2.0 5 votes vote down vote up
@ParamValid
@Transactional
public void modifyLoginPwd(ModifyLoginPwdParam param) {
	UserAccount userAccount = userAccountRepo.getOne(param.getUserAccountId());
	BCryptPasswordEncoder pwdEncoder = new BCryptPasswordEncoder();
	if (!pwdEncoder.matches(param.getOldLoginPwd(), userAccount.getLoginPwd())) {
		throw new BizException(BizError.旧的登录密码不正确);
	}
	modifyLoginPwd(param.getUserAccountId(), param.getNewLoginPwd());
}
 
Example 17
Source Project: SpringAll   Source File: AuthorizationServerConfig.java    License: MIT License 5 votes vote down vote up
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
            .withClient("test1")
            .secret(new BCryptPasswordEncoder().encode("test1111"))
            .authorizedGrantTypes("password", "refresh_token")
            .accessTokenValiditySeconds(3600)
            .refreshTokenValiditySeconds(864000)
            .scopes("all", "a", "b", "c")
        .and()
            .withClient("test2")
            .secret(new BCryptPasswordEncoder().encode("test2222"))
            .accessTokenValiditySeconds(7200);
}
 
Example 18
Source Project: MaxKey   Source File: SCryptPasswordEncoderTest.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	// TODO Auto-generated method stub
	BCryptPasswordEncoder pe=new BCryptPasswordEncoder();
	//String c="$e0801$7Holo9EgzBeg5xf/WLZu3/5IQwOyEPDLJPgMXkF9jnekBrbQUMt4CF9O2trkz3zBCnCLpUMR437q/AjQ5TTToA==$oYB8KRSxAsxkKkt5r79W6r6P0wTUcKwGye1ivXRN0Ts="
	//;
	System.out.println(pe.encode("admin"));
		//	System.out.println(pe.encode("shimingxy")+"_password");
			//System.out.println(pe.matches("shimingxy"+"_password", c));
}
 
Example 19
Source Project: runscore   Source File: UserAccountService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 账号注册
 * 
 * @param param
 */
@ParamValid
@Transactional
public void register(UserAccountRegisterParam param) {
	UserAccount userAccount = userAccountRepo.findByUserName(param.getUserName());
	if (userAccount != null) {
		throw new BizException(BizError.用户名已存在);
	}
	param.setLoginPwd(new BCryptPasswordEncoder().encode(param.getLoginPwd()));
	param.setMoneyPwd(new BCryptPasswordEncoder().encode(param.getMoneyPwd()));
	UserAccount newUserAccount = param.convertToPo();
	RegisterSetting setting = registerSettingRepo.findTopByOrderByLatelyUpdateTime();
	if (!setting.getRegisterEnabled()) {
		throw new BizException(BizError.未开放注册功能);
	}
	if (setting.getInviteRegisterEnabled()) {
		InviteCode inviteCode = inviteCodeRepo
				.findTopByCodeAndPeriodOfValidityGreaterThanEqual(param.getInviteCode(), new Date());
		if (inviteCode == null) {
			throw new BizException(BizError.邀请码不存在或已失效);
		}
		newUserAccount.updateInviteInfo(inviteCode);
	} else {
		newUserAccount.setRebate(setting.getRegitserDefaultRebate());
	}
	userAccountRepo.save(newUserAccount);
}
 
Example 20
@Bean
public PasswordEncoder passwordEncoder() {
	return new BCryptPasswordEncoder();
}
 
Example 21
Source Project: SpringAll   Source File: BrowserSecurityConfig.java    License: MIT License 4 votes vote down vote up
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
 
Example 22
Source Project: Spring-Security-Third-Edition   Source File: SecurityConfig.java    License: MIT License 4 votes vote down vote up
/**
 * BCryptPasswordEncoder password encoder
 * @return
 */
@Bean
public PasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder(4);
}
 
Example 23
public static String encode(String password) {
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(4);
    String encodedPassword = encoder.encode(password);
    return encodedPassword;
}
 
Example 24
public static String encode(String password) {
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    return encoder.encode(password);
}
 
Example 25
@Bean
public PasswordEncoder passwordEncoder() {
	return new BCryptPasswordEncoder();
}
 
Example 26
Source Project: Spring-5.0-Projects   Source File: WebSecurityConfig.java    License: MIT License 4 votes vote down vote up
@Bean
public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
 
Example 27
Source Project: Spring-5.0-Projects   Source File: UserConfiguration.java    License: MIT License 4 votes vote down vote up
@Bean
public PasswordEncoder passwordEncoder() {
 return new BCryptPasswordEncoder();
}
 
Example 28
Source Project: SpringAll   Source File: BrowserSecurityConfig.java    License: MIT License 4 votes vote down vote up
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
 
Example 29
Source Project: Spring-Boot-Book   Source File: WebSecurityConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(Service()).passwordEncoder(new BCryptPasswordEncoder() {
    });
}
 
Example 30
@Bean
public PasswordEncoder loadPasswordEncoder() {
    return new BCryptPasswordEncoder();
}