Search in sources :

Example 21 with BCryptPasswordEncoder

use of org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder in project cas by apereo.

the class PasswordEncoderUtils method newPasswordEncoder.

/**
 * New password encoder password encoder.
 *
 * @param properties         the properties
 * @param applicationContext the application context
 * @return the password encoder
 */
@SuppressWarnings("java:S5344")
public static PasswordEncoder newPasswordEncoder(final PasswordEncoderProperties properties, final ApplicationContext applicationContext) {
    val type = properties.getType();
    if (StringUtils.isBlank(type)) {
        LOGGER.trace("No password encoder type is defined, and so none shall be created");
        return NoOpPasswordEncoder.getInstance();
    }
    if (type.endsWith(".groovy")) {
        LOGGER.trace("Creating Groovy-based password encoder at [{}]", type);
        val resource = applicationContext.getResource(type);
        return new GroovyPasswordEncoder(resource, applicationContext);
    }
    if (type.contains(".")) {
        try {
            LOGGER.debug("Configuration indicates use of a custom password encoder [{}]", type);
            val clazz = (Class<PasswordEncoder>) Class.forName(type);
            return clazz.getDeclaredConstructor().newInstance();
        } catch (final Exception e) {
            val msg = "Falling back to a no-op password encoder as CAS has failed to create " + "an instance of the custom password encoder class " + type;
            LoggingUtils.error(LOGGER, msg, e);
            return NoOpPasswordEncoder.getInstance();
        }
    }
    val encoderType = PasswordEncoderProperties.PasswordEncoderTypes.valueOf(type);
    switch(encoderType) {
        case DEFAULT:
            LOGGER.debug("Creating default password encoder with encoding alg [{}] and character encoding [{}]", properties.getEncodingAlgorithm(), properties.getCharacterEncoding());
            return new DefaultPasswordEncoder(properties.getEncodingAlgorithm(), properties.getCharacterEncoding());
        case STANDARD:
            LOGGER.debug("Creating standard password encoder with the secret defined in the configuration");
            return new StandardPasswordEncoder(properties.getSecret());
        case BCRYPT:
            LOGGER.debug("Creating BCRYPT password encoder given the strength [{}] and secret in the configuration", properties.getStrength());
            if (StringUtils.isBlank(properties.getSecret())) {
                LOGGER.debug("Creating BCRYPT encoder without secret");
                return new BCryptPasswordEncoder(properties.getStrength());
            }
            LOGGER.debug("Creating BCRYPT encoder with secret");
            return new BCryptPasswordEncoder(properties.getStrength(), RandomUtils.getNativeInstance());
        case SCRYPT:
            LOGGER.debug("Creating SCRYPT encoder");
            return new SCryptPasswordEncoder();
        case SSHA:
            LOGGER.warn("Creating SSHA encoder; digest based password encoding is not considered secure. " + "This strategy is here to support legacy implementations and using it is considered insecure.");
            return new LdapShaPasswordEncoder();
        case PBKDF2:
            if (StringUtils.isBlank(properties.getSecret())) {
                LOGGER.trace("Creating PBKDF2 encoder without secret");
                return new Pbkdf2PasswordEncoder();
            }
            return new Pbkdf2PasswordEncoder(properties.getSecret(), properties.getStrength(), HASH_WIDTH);
        case GLIBC_CRYPT:
            val hasSecret = StringUtils.isNotBlank(properties.getSecret());
            val msg = String.format("Creating glibc CRYPT encoder with encoding alg [%s], strength [%s] and %ssecret", properties.getEncodingAlgorithm(), properties.getStrength(), BooleanUtils.toString(hasSecret, StringUtils.EMPTY, "without "));
            LOGGER.debug(msg);
            return new GlibcCryptPasswordEncoder(properties.getEncodingAlgorithm(), properties.getStrength(), properties.getSecret());
        case NONE:
        default:
            LOGGER.trace("No password encoder shall be created given the requested encoder type [{}]", type);
            return NoOpPasswordEncoder.getInstance();
    }
}
Also used : lombok.val(lombok.val) StandardPasswordEncoder(org.springframework.security.crypto.password.StandardPasswordEncoder) GlibcCryptPasswordEncoder(org.apereo.cas.util.crypto.GlibcCryptPasswordEncoder) SCryptPasswordEncoder(org.springframework.security.crypto.scrypt.SCryptPasswordEncoder) Pbkdf2PasswordEncoder(org.springframework.security.crypto.password.Pbkdf2PasswordEncoder) UtilityClass(lombok.experimental.UtilityClass) DefaultPasswordEncoder(org.apereo.cas.util.crypto.DefaultPasswordEncoder) LdapShaPasswordEncoder(org.springframework.security.crypto.password.LdapShaPasswordEncoder) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder)

Example 22 with BCryptPasswordEncoder

use of org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder in project cas by apereo.

the class QueryDatabaseAuthenticationHandlerTests method verifyBCryptSuccess.

/**
 * This test proves that in case BCRYPT and
 * using raw password test can authenticate
 */
@Test
public void verifyBCryptSuccess() throws Exception {
    val encoder = new BCryptPasswordEncoder(6, RandomUtils.getNativeInstance());
    val sql = SQL.replace("*", '\'' + encoder.encode("pswbc2") + "' password");
    val properties = new QueryJdbcAuthenticationProperties().setSql(sql).setFieldPassword(PASSWORD_FIELD);
    val q = new QueryDatabaseAuthenticationHandler(properties, null, PrincipalFactoryUtils.newPrincipalFactory(), this.dataSource, new HashMap<>(0));
    q.setPasswordEncoder(encoder);
    assertNotNull(q.authenticate(CoreAuthenticationTestUtils.getCredentialsWithDifferentUsernameAndPassword("user3", "pswbc2")));
}
Also used : lombok.val(lombok.val) QueryJdbcAuthenticationProperties(org.apereo.cas.configuration.model.support.jdbc.authn.QueryJdbcAuthenticationProperties) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) Test(org.junit.jupiter.api.Test)

Example 23 with BCryptPasswordEncoder

use of org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder in project vft-capture by videofirst.

the class SecurityUtils method checkCreatePassword.

/**
 * Create password if first command arg is `-pwd`.
 */
public static void checkCreatePassword(String[] args) {
    // Check to see if we're trying to change password
    if ((args.length == 1 || args.length == 2) && "-pwd".equals(args[0])) {
        System.out.println("=============================");
        System.out.println("VF CAPTURE - PASSWORD ENCODER");
        System.out.println("=============================");
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(SecurityConfiguration.BCRYPT_STRENGTH);
        if (args.length == 2) {
            System.out.println("\nEncoded output [ " + passwordEncoder.encode(args[1]) + " ]\n");
            System.exit(0);
        }
        while (true) {
            try {
                System.out.print("\nPlease enter password (or q to exit): - ");
                System.out.flush();
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String input = br.readLine();
                if ("q".equalsIgnoreCase(input)) {
                    System.exit(0);
                }
                System.out.println("\nEncoded output [ " + passwordEncoder.encode(input) + " ]\n");
            } catch (IOException e) {
                System.out.println("Error reading line " + e.getMessage());
            }
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder)

Example 24 with BCryptPasswordEncoder

use of org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder in project hono by eclipse.

the class CredentialsManagementIT method testAddCredentialsFailsForBCryptWithTooManyIterations.

/**
 * Verifies that the service returns a 400 status code for an add credentials request with hashed password
 * credentials that use a BCrypt hash with more than the configured max iterations.
 *
 * @param context The vert.x test context.
 */
@Test
public void testAddCredentialsFailsForBCryptWithTooManyIterations(final VertxTestContext context) {
    // GIVEN a hashed password using bcrypt with more than the configured max iterations
    final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(IntegrationTestSupport.MAX_BCRYPT_COST_FACTOR + 1);
    final PasswordSecret secret = new PasswordSecret();
    secret.setHashFunction(CredentialsConstants.HASH_FUNCTION_BCRYPT);
    secret.setPasswordHash(encoder.encode("thePassword"));
    final PasswordCredential credential = new PasswordCredential(authId, List.of(secret));
    // WHEN adding the credentials
    testAddCredentialsWithErroneousPayload(context, new JsonArray().add(JsonObject.mapFrom(credential)), // THEN the request fails with 400
    HttpURLConnection.HTTP_BAD_REQUEST);
}
Also used : JsonArray(io.vertx.core.json.JsonArray) PasswordSecret(org.eclipse.hono.service.management.credentials.PasswordSecret) PasswordCredential(org.eclipse.hono.service.management.credentials.PasswordCredential) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) Test(org.junit.jupiter.api.Test)

Example 25 with BCryptPasswordEncoder

use of org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder in project fw-cloud-framework by liuweijw.

the class UserServiceImpl method addUserAndRoleDept.

@Override
@Transactional
@CacheEvict(allEntries = true)
public boolean addUserAndRoleDept(UserForm userForm) {
    User user = new User();
    user.setCreateTime(new Date());
    user.setStatu(0);
    user.setDeptId(userForm.getDeptId());
    user.setPassword(new BCryptPasswordEncoder().encode(userForm.getPassword().trim()));
    user.setUpdateTime(new Date());
    user.setUsername(userForm.getUsername().trim());
    user.setMobile(userForm.getMobile());
    User dbUser = this.userRepository.saveAndFlush(user);
    UserRole uRole = new UserRole();
    uRole.setRoleId(userForm.getRoleId());
    uRole.setUserId(dbUser.getUserId());
    this.userRoleRepository.saveAndFlush(uRole);
    return true;
}
Also used : User(com.github.liuweijw.business.admin.domain.User) AuthUser(com.github.liuweijw.system.api.model.AuthUser) QUser(com.github.liuweijw.business.admin.domain.QUser) QUserRole(com.github.liuweijw.business.admin.domain.QUserRole) UserRole(com.github.liuweijw.business.admin.domain.UserRole) Date(java.util.Date) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) CacheEvict(org.springframework.cache.annotation.CacheEvict) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

BCryptPasswordEncoder (org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder)48 PasswordEncoder (org.springframework.security.crypto.password.PasswordEncoder)18 Test (org.junit.jupiter.api.Test)7 KeystorePasswordHolder (won.owner.model.KeystorePasswordHolder)7 User (won.owner.model.User)7 SCryptPasswordEncoder (org.springframework.security.crypto.scrypt.SCryptPasswordEncoder)6 DelegatingPasswordEncoder (org.springframework.security.crypto.password.DelegatingPasswordEncoder)5 NoOpPasswordEncoder (org.springframework.security.crypto.password.NoOpPasswordEncoder)5 Pbkdf2PasswordEncoder (org.springframework.security.crypto.password.Pbkdf2PasswordEncoder)5 StandardPasswordEncoder (org.springframework.security.crypto.password.StandardPasswordEncoder)5 User (com.github.liuweijw.business.admin.domain.User)4 HashMap (java.util.HashMap)4 Transactional (org.springframework.transaction.annotation.Transactional)4 KeystoreHolder (won.owner.model.KeystoreHolder)4 ExpensiveSecureRandomString (won.protocol.util.ExpensiveSecureRandomString)4 PrePermissions (com.github.liuweijw.business.commons.web.aop.PrePermissions)3 Date (java.util.Date)3 lombok.val (lombok.val)3 Bean (org.springframework.context.annotation.Bean)3 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)3