本文整理汇总了Java中org.springframework.security.crypto.bcrypt.BCrypt类的典型用法代码示例。如果您正苦于以下问题:Java BCrypt类的具体用法?Java BCrypt怎么用?Java BCrypt使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
BCrypt类属于org.springframework.security.crypto.bcrypt包,在下文中一共展示了BCrypt类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()));
}
}
示例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()));
}
示例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;
}
示例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;
}
示例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);
}
}
示例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;
}
示例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
}
示例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;
}
示例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;
}
示例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;
}
示例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));
}
示例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);
}
}
示例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);
}
示例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);
}
示例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;
}