• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java BCrypt类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中org.springframework.security.crypto.bcrypt.BCrypt的典型用法代码示例。如果您正苦于以下问题:Java BCrypt类的具体用法?Java BCrypt怎么用?Java BCrypt使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



BCrypt类属于org.springframework.security.crypto.bcrypt包,在下文中一共展示了BCrypt类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: authChangepwdPut

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
@Transactional

    public void authChangepwdPut(ResetPwd body) throws ApiException {

        String token = body.getToken();
//        System.out.println("token: " + token);

        if (body == null) {
            throw new ApiException(400, "Bad reset password data");
        }
        // retrieve user with this secret
        User user = userRep.findBySecret(token);

        if (user == null) {
            throw new ApiException(400, "Bad reset password data");
        }
        // Check if token expired
        if (user.getSecretCreation().plusDays(1).getMillis() < DateTime.now().getMillis()) {
            throw new ApiException(400, "Bad reset password data");
        } else {

            user.setSecret(null);
            user.setSecretCreation(null);
            user.setPassword(BCrypt.hashpw(body.getPassword(), BCrypt.gensalt()));
        }
    }
 
开发者ID:jrtechnologies,项目名称:yum,代码行数:27,代码来源:AuthService.java


示例2: testAuthChangepwdPut204

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
@Test
public void testAuthChangepwdPut204() throws Exception {

    given(mockUserRepository.findBySecret("b136e1d2-0e74-45d4-bf52-c01685623ac9")).willReturn(mockUserReset);

    // We perform the API call, and check that the response status code, and the JSON response are corrects
    mockMvc.perform(put("/api/auth/changepwd")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content("{\n"
                    + "  \"token\": \"b136e1d2-0e74-45d4-bf52-c01685623ac9\",\n"
                    + "  \"password\": \"lazos1234\"\n"
                    + "}"))
            .andExpect(status().isNoContent());

    // we verify that we called findAll method once only on the repo.
    verify(mockUserRepository, times(1)).findBySecret("b136e1d2-0e74-45d4-bf52-c01685623ac9");
    // we verify that we didnt call anything else on the repo
    verifyNoMoreInteractions(mockUserRepository);
    
    // we verify that the password changed as expected     
    assertTrue(BCrypt.checkpw(mockModifiedUserReset.getPassword(), mockUserRepository.findBySecret("b136e1d2-0e74-45d4-bf52-c01685623ac9").getPassword()));

}
 
开发者ID:jrtechnologies,项目名称:yum,代码行数:24,代码来源:AuthApiControllerTest.java


示例3: storeMessage

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
String storeMessage(final String senderId, final String message,
                    final KeyIv encryptionKey, final List<SecretFile> files,
                    final byte[] linkSecret, final String password, final Instant expiration) {

    Objects.requireNonNull(senderId, "senderId must not be null");

    final String receiverId = newRandomId();

    final String hashedPassword =
        password != null ? BCrypt.hashpw(password, BCrypt.gensalt()) : null;

    final ReceiverMessage receiverMessage = new ReceiverMessage(
        receiverId,
        senderId,
        hashedPassword,
        encryptKey(linkSecret,
            MoreObjects.firstNonNull(password, DEFAULT_PASSWORD), encryptionKey),
        encryptMessage(message, encryptionKey.getKey()),
        files,
        expiration
    );

    receiverMsgRepository.create(receiverId, receiverMessage);

    return receiverId;
}
 
开发者ID:osiegmar,项目名称:setra,代码行数:27,代码来源:MessageSenderService.java


示例4: save

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
@Override
public int save(User model) {
    logger.info("[UserService->save] start username is {} ...", model.getUsername());
    Assert.hasText(model.getUsername(), "请输入用户名");
    if (findBy("username", model.getUsername()) != null) {
        throw new ServiceException("用户名不允许重复");
    }
    String password = model.getPassword();
    model.setVersion(0);
    model.setUserType(UserType.USER.value());
    String mysalt = new BCryptPasswordEncoder().encode(password);
    model.setPassword(BCrypt.hashpw(password, mysalt));
    int rtn = super.save(model);
    userAuthorityService.grantNormalAuth(model.getId());
    logger.info("[UserService->save] end username is {} ...", model.getUsername());
    return rtn;
}
 
开发者ID:pandboy,项目名称:pingguopai,代码行数:18,代码来源:UserServiceImpl.java


示例5: init

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
@PostConstruct
public void init() {
  log.debug("Creating initial Users...");

  User admin = userRepository.findFirstByUsername("admin");
  if (!userExists("admin")) {
    User ob_admin = new User();
    ob_admin.setUsername("admin");
    ob_admin.setEnabled(true);
    ob_admin.setPassword(BCrypt.hashpw(adminPwd, BCrypt.gensalt(12)));
    Set<Role> roles = new HashSet<>();
    Role role = new Role();
    role.setRole(RoleEnum.ADMIN);
    role.setProject("*");
    roles.add(role);
    ob_admin.setRoles(roles);
    createUser(ob_admin);
  } else {
    log.debug("Admin user exists already.");
  }

  log.debug("Users in the DB: ");
  for (User user : userRepository.findAll()) {
    log.debug("" + user);
  }
}
 
开发者ID:openbaton,项目名称:NFVO,代码行数:27,代码来源:CustomUserDetailsService.java


示例6: add

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
@Override
public User add(User user) throws PasswordWeakException, BadRequestException {
  log.debug("Adding new user: " + user);

  if (customUserDetailsService.userExists(user.getUsername())) {
    throw new BadRequestException("Username exists already");
  }

  checkIntegrity(user);

  if (checkStrength) {
    Utils.checkPasswordIntegrity(user.getPassword());
  }

  user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt(12)));
  customUserDetailsService.createUser(user);
  return user;
}
 
开发者ID:openbaton,项目名称:NFVO,代码行数:19,代码来源:UserManagement.java


示例7: loginUser

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
/**
 * Login user.
 *
 * @param message
 *          the message
 * @return the response
 */
protected Response loginUser(UserMessage message) {
  String userName = message.getUserName();
  User user = assist.expectedUser(userName);

  SystemIdKey id = message.getSystemId();
  switch (user.getState()) {
  case ACTIVE:
    break;
  default:
    fail(getResponseContext(CANNOT_DELETE_USER, id), userName + " is in state " + user.getState());
  }

  boolean ok = BCrypt.checkpw(message.getOldPassword(), user.getPasswordHash());

  log.info("Login for {} is {}", userName, ok);

  setLocale(message);

  //@formatter:off
  return ok ? 
      createSession(message, user) : 
      failure(getResponseContext(INVALID_PASSWORD, id), message, "Password is invalid");
  //@formatter:on
}
 
开发者ID:mrstampy,项目名称:gameboot,代码行数:32,代码来源:UserMessageProcessor.java


示例8: encode

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
public String encode(final String value, final CipherAlgorithm cipherAlgorithm)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException {

    String encodedValue = null;

    if (value != null) {
        if (cipherAlgorithm == null || cipherAlgorithm == CipherAlgorithm.AES) {
            final byte[] cleartext = value.getBytes(StandardCharsets.UTF_8);

            final Cipher cipher = Cipher.getInstance(CipherAlgorithm.AES.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);

            encodedValue = new String(Base64.getEncoder().encode(cipher.doFinal(cleartext)));
        } else if (cipherAlgorithm == CipherAlgorithm.BCRYPT) {
            encodedValue = BCrypt.hashpw(value, BCrypt.gensalt());
        } else {
            encodedValue = getDigester(cipherAlgorithm).digest(value);
        }
    }

    return encodedValue;
}
 
开发者ID:apache,项目名称:syncope,代码行数:24,代码来源:Encryptor.java


示例9: verify

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
public boolean verify(final String value, final CipherAlgorithm cipherAlgorithm, final String encodedValue) {
    boolean res = false;

    try {
        if (value != null) {
            if (cipherAlgorithm == null || cipherAlgorithm == CipherAlgorithm.AES) {
                res = encode(value, cipherAlgorithm).equals(encodedValue);
            } else if (cipherAlgorithm == CipherAlgorithm.BCRYPT) {
                res = BCrypt.checkpw(value, encodedValue);
            } else {
                res = getDigester(cipherAlgorithm).matches(value, encodedValue);
            }
        }
    } catch (Exception e) {
        LOG.error("Could not verify encoded value", e);
    }

    return res;
}
 
开发者ID:apache,项目名称:syncope,代码行数:20,代码来源:Encryptor.java


示例10: encryptField

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
private String encryptField(String plainValue, String encryptionType) {
		if (ONE_WAY_HINT.equals(encryptionType)) {
			String salt = BCrypt.gensalt();
			String encryptedValue = BCrypt.hashpw(plainValue, salt);
			return encryptedValue;
		} else if (TWO_WAY_HINT.equals(encryptionType)) {
			try {
				return Base64.encodeBase64String(plainValue.getBytes(CHARSET));
			} catch (UnsupportedEncodingException exception) {
				System.out.println("[easy-men] problem with the encoding " + CHARSET);
				return null;
			}
//			//	AES encryption, requires Java7
//			String salt = KeyGenerators.string().generateKey();
//			TextEncryptor textEncryptor = Encryptors.queryableText(_password, salt);
//			return new StringBuilder(textEncryptor.encrypt(plainValue)).append(":").append(salt).toString();
		}
		return null;
	}
 
开发者ID:bioko,项目名称:system,代码行数:20,代码来源:ProdEntityEncryptionService.java


示例11: simpleEncryptionSaltyTest

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
@Test
public void simpleEncryptionSaltyTest() {
	ProdEntityEncryptionService encrypter = new ProdEntityEncryptionService();
	
	Login login = new LoginBuilder().loadDefaultExample().build(false);
	Login encryptedLogin = encrypter.encryptEntity(login);

	assertThat(encryptedLogin, notNullValue());
	assertThat(encryptedLogin.fields().keys(), contains(login.fields().keys().toArray(new String[0])));
	
	for (String aFieldName : login.fields().keys()) {
		if (!aFieldName.equals(Login.PASSWORD)) {
			assertThat(encryptedLogin.get(aFieldName), is(equalTo(login.get(aFieldName))));
		}
	}
	
	assertThat(encryptedLogin.get(Login.PASSWORD), is(not(equalTo(login.get(Login.PASSWORD)))));
	
	assertThat(BCrypt.checkpw(login.get(Login.PASSWORD).toString(), encryptedLogin.get(Login.PASSWORD).toString()), is(true));
	assertThat(BCrypt.checkpw("A wrong password", encryptedLogin.get(Login.PASSWORD).toString()), is(false));
}
 
开发者ID:bioko,项目名称:system,代码行数:22,代码来源:EntityEncrypterTest.java


示例12: updateAuthenticationDetails

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
/**
 * Updates the modelwrapper authentication details.
 * @param username The new username.
 * @param password The new password.
 * @param passwordConfirmation Confirmation of the new password.
 * @return 204 for success, 400 for failure.
 */
@RequestMapping(value = "/auth", method = RequestMethod.POST)
public ResponseEntity updateAuthenticationDetails(String username, String password, String passwordConfirmation) {
    boolean validRequest =
        !StringUtils.isEmpty(username) && USERNAME_REGEX.matcher(username).matches() &&
        !StringUtils.isEmpty(password) && PASSWORD_REGEX.matcher(password).matches() &&
        password.equals(passwordConfirmation);

    if (validRequest) {
        String passwordHash = BCrypt.hashpw(password, BCrypt.gensalt());
        configurationService.setAuthenticationDetails(username, passwordHash);

        // Respond with a 204, this is equivalent to a 200 (OK) but without any content.
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    } else {
        return new ResponseEntity(HttpStatus.BAD_REQUEST);
    }
}
 
开发者ID:SEEG-Oxford,项目名称:ABRAID-MP,代码行数:25,代码来源:IndexController.java


示例13: updateAuthenticationDetailsCallConfigurationServiceWithCorrectParams

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
@Test
public void updateAuthenticationDetailsCallConfigurationServiceWithCorrectParams() {
    // Arrange
    ModelWrapperConfigurationService mockConfService = mock(ModelWrapperConfigurationService.class);
    IndexController target = new IndexController(mockConfService);
    String expectedPassword = "PasswordOne1";
    String expectedUser = "user";

    // Act
    ResponseEntity result = target.updateAuthenticationDetails(expectedUser, expectedPassword, expectedPassword);

    // Assert
    ArgumentCaptor<String> usernameCaptor = captorForClass(String.class);
    ArgumentCaptor<String> passwordCaptor = captorForClass(String.class);
    verify(mockConfService).setAuthenticationDetails(usernameCaptor.capture(), passwordCaptor.capture());
    assertThat(usernameCaptor.getValue()).isEqualTo(expectedUser);
    assertThat(BCrypt.checkpw(expectedPassword, passwordCaptor.getValue())).isTrue();
    assertThat(result.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
}
 
开发者ID:SEEG-Oxford,项目名称:ABRAID-MP,代码行数:20,代码来源:IndexControllerTest.java


示例14: approveAccount

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
/**
 * Assume password has been set as plain text
 * @param account
 */
public void approveAccount(final Account account) {
	this.logger.info("AccountService.approveAccount");
	// Create random salt and store a hashed password
	final String textPassword = account.getHashedPass();
	final String salt = BCrypt.gensalt(16);
	final String hashedPassword = BCrypt.hashpw(textPassword, salt);
	account.setSalt(salt);
	account.setHashedPass(hashedPassword);
	// status is now approved
	account.setStatus(AccountStatus.STATUS_APPROVED.name());
	this.accountRepo.save(account);
}
 
开发者ID:llop,项目名称:porra-joc-eda,代码行数:17,代码来源:AccountService.java


示例15: authenticate

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
static boolean authenticate(String username, String password) {
	boolean authenticated = false;
	if (Properties.getString("ldap.server") == null) {
		Person user = Person.find("byUsername", username).first();
		authenticated = user != null && user.password != null && BCrypt.checkpw(password, user.password);
	} else {
		if (!password.isEmpty()) {
			Hashtable<String, String> env = new Hashtable<String, String>();
			env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
			env.put(Context.PROVIDER_URL, Properties.getString("ldap.server"));
			env.put(Context.SECURITY_PRINCIPAL, String.format("%[email protected]%s", username, Properties.getString("ldap.domain")));
			env.put(Context.SECURITY_CREDENTIALS, password);
			try {
				new InitialDirContext(env);
				authenticated = true;
			} catch (NamingException e) {
				Logger.info("LDAP authentication failed for %s", username);
			}
		}
	}
	return authenticated;
}
 
开发者ID:mwoodbri,项目名称:MRIdb,代码行数:23,代码来源:Security.java


示例16: authRegisterPost

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
@Transactional
public void authRegisterPost(UserReg body) throws ApiException {
    try {
        // if Role not in enum UserRole throws exception 
        //UserRole userRole = convertToUserRole(body.getRole());
        UserRole userRole = convertToUserRole("hungry");
        String email = body.getEmail();
        if (userRep.findByEmail(email) != null) {
            //    return new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED); 
            throw new ApiException(412, "User already exists");
        }
        User user = new User();
        user.setEmail(email);
        user.setFirstEmail(email);
        user.setFirstName(body.getFirstName());
        user.setLastName(body.getLastName());
        // Encrypt password and set it to User D.A.O.
        user.setPassword(BCrypt.hashpw(body.getPassword(), BCrypt.gensalt()));
        user.setUserRole(userRole);
        user.setApproved(false);
        user.setLastEdit(DateTime.now());
        user.setRegistrationDate(LocalDate.now());
        user.setBalance(BigDecimal.ZERO);
        user.setOrderNtf(true);
        user.setOrderModifyNtf(true);
        user.setAdminOrderNtf(true);
        user.setAdminOrderModifyNtf(true);
        user.setBalanceNtf(true);
        userRep.save(user);
        // The email service is injected and sends emails to all admins 

        if (emailService != null) {
            emailService.sendNewUserEmailToAllAdmins(user);
        }
        // if Role not in enum UserRole catches this exception  
    } catch (IllegalArgumentException e) {
        throw new ApiException(400, "Bad registration data");
    }
}
 
开发者ID:jrtechnologies,项目名称:yum,代码行数:40,代码来源:AuthService.java


示例17: usersPost

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
@Transactional
public com.jrtechnologies.yum.data.entity.User usersPost(UserReg user) throws ApiException, Exception {
    UserRole userRole = convertToUserRole(user.getRole());
    String email = user.getEmail();
    //Check if user already exists
    if (userRepo.findByEmail(email) != null) {
        throw new ApiException(412, "User already exists");
    }
    //Check if name is empty.
    String firstName = user.getFirstName().trim();
    String lastName = user.getLastName().trim();
    if (firstName.equals("") || lastName.equals("")) {
        throw new ApiException(400, "Validation Failed");
    }
    //Create entity type user.
    com.jrtechnologies.yum.data.entity.User userEntity = new com.jrtechnologies.yum.data.entity.User();
    userEntity.setFirstName(firstName);
    userEntity.setLastName(lastName);
    userEntity.setEmail(email);
    userEntity.setFirstEmail(email);
    userEntity.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt())); //Crypt password 
    userEntity.setUserRole(userRole);
    userEntity.setRegistrationDate(LocalDate.now());
    userEntity.setLastEdit(DateTime.now());
    userEntity.setBalance(BigDecimal.ZERO);
    userEntity.setOrderNtf(true);
    userEntity.setOrderModifyNtf(true);
    userEntity.setAdminOrderNtf(true);
    userEntity.setAdminOrderModifyNtf(true);
    userEntity.setBalanceNtf(true);
    userRepo.save(userEntity); // Save user in database
    return userEntity;
}
 
开发者ID:jrtechnologies,项目名称:yum,代码行数:34,代码来源:UsersService.java


示例18: createHash

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
@Override
public String createHash(String password) throws CustomException {
	logger.trace("Création du Hash avec BCrypt");
	String pwd = BCrypt.hashpw(password, BCrypt.gensalt());
	if (pwd.length()>150){
		throw new CustomException();
	}
	return pwd;
}
 
开发者ID:EsupPortail,项目名称:esup-ecandidat,代码行数:10,代码来源:PasswordHashServiceBCrypt.java


示例19: validatePassword

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
private void validatePassword(final String receiverId, final String password,
                              final ReceiverMessage receiverMessage) {

    if (receiverMessage.getPassword() == null) {
        throw new IllegalStateException("Message is not password protected");
    }

    final int decryptAttempts = receiverMessage.incrementDecryptAttempt();

    receiverMsgRepository.update(receiverMessage.getId(), receiverMessage);

    if (BCrypt.checkpw(password, receiverMessage.getPassword())) {
        return;
    }

    // invalid password ...

    if (decryptAttempts > 2) {
        // burn if too many failed attempts
        receiverMsgRepository.delete(receiverId);

        // inform the sender about invalidation
        updateSenderMessageInvalidated(receiverMessage.getSenderId());

        throw new MessageNotFoundException();
    }

    throw new IllegalStateException("Incorrect password");
}
 
开发者ID:osiegmar,项目名称:setra,代码行数:30,代码来源:MessageReceiverService.java


示例20: tokenProcessingFilter

import org.springframework.security.crypto.bcrypt.BCrypt; //导入依赖的package包/类
private Filter tokenProcessingFilter() {
	return new BasicAuthenticationFilter(new AuthenticationManager() {
		
		@Override
		public Authentication authenticate(Authentication authentication)
				throws AuthenticationException {
			User user = userRepository.findByEmail(authentication.getName());
			if (user == null || user.getUsr() == null) {
				throw new BadCredentialsException("Invalid credentials! \n\n Please, login again.");
			}
			String token = user.getUsr().getDeviceToken();
			String credentials = (String) authentication.getCredentials();
			try {
				if(!BCrypt.checkpw(token, credentials)) {
					throw new BadCredentialsException("Invalid credentials! \n\n Please, login again.");
				}
			} catch (IllegalArgumentException e) {
				throw new BadCredentialsException("Invalid credentials! \n\n Please, login again.");
			}
			Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
			authorities.add(new SimpleGrantedAuthority(user.getRole().name()));
			Authentication ret = new PreAuthenticatedAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), authorities );
			return ret;
		}
	}) {
		@Override
		protected boolean isIgnoreFailure() {
			return true;
		}
	};
}
 
开发者ID:eduyayo,项目名称:gamesboard,代码行数:32,代码来源:RestLoginSecurityContext.java



注:本文中的org.springframework.security.crypto.bcrypt.BCrypt类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java ClipboardTransferable类代码示例发布时间:2022-05-21
下一篇:
Java Features类代码示例发布时间:2022-05-21
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap