Java 如何更改H2数据库的密码加密?
我的Spring Boot项目有以下配置文件:Java 如何更改H2数据库的密码加密?,java,spring-boot,h2,Java,Spring Boot,H2,我的Spring Boot项目有以下配置文件: @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; @Autowired
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Autowired
private PasswordEncoder passwordEncoder;
@Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder(8);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/registration", "/activate/*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService)
.passwordEncoder(passwordEncoder);
}
}
我还有data.sql文件,但我需要对这些密码进行编码:
insert into users (email, username, password, is_enabled)
values ('admin@gmail.com', 'admin', 'admin', true),
('user@gmail.com', 'user', 'password', true),
('user2@gmail.com', 'user2', 'password', true);
insert into user_role (user_id, roles)
values (100000, 'ADMIN'),
(100000, 'USER'),
(100001, 'USER'),
(100002, 'USER');
对于“PostgreSQL”,我可以这样设置编码:
CREATE EXTENSION IF NOT EXISTS pgcrypto;
UPDATE users SET password = crypt(password, gen_salt('bf', 8));
但它不适用于H2数据库。如何修复它并对密码进行编码?SQL没有任何可移植的方法,但有些数据库有自己的功能。在H2中,您可以使用生成密码哈希
updateuserssetpassword=HASH('SHA256',PASSWORD,1000);
从USERNAME=?并且启用了_,密码=散列('SHA256',?,1000);
您还可以使用该函数生成salt,以将其与密码连接起来,但您必须将salt单独存储在其自己的列中,或使用分隔符存储在同一列中(或使用哈希函数的已知长度)
updateusers SET PASSWORD=(@S:=SECURE_RAND(16))||散列('SHA256',@S||PASSWORD,1000);
从用户名为'user'的用户中选择*
和散列('SHA256',子字符串(密码从1到32)| |'密码',1000)
=子字符串(来自33的密码);
您还可以编写用户定义的函数来模拟PostgreSQL中的函数
更可靠的解决方案是使用Java代码,它将不依赖于您当前使用的数据库
final int key length=256/8;
最终字符串算法=“PBKDF2WithHmacSHA256”;
最终长度=16;
最终整数=1000;
SecureRandom sr=SecureRandom.getInstanceStrong();
SecretKeyFactory skf=SecretKeyFactory.getInstance(算法);
//编码
字符串password=“test”;
字节[]salt=sr.generateSeed(saltLength);
字节[]encodedPassword=skf
.generateSecret(新的PBEKeySpec(password.toCharArray(),salt,numIterations,keyLength*8))
.getEncoded();
byte[]passwordHash=Arrays.copyOf(salt,saltLength+keydlength);
System.arraycopy(encodedPassword,0,passwordHash,saltLength,keyLength);
//检查
字符串password2=“test”;
salt=Arrays.copyOf(passwordHash,saltLength);
字节[]encodedPassword2=skf
.generateScret(新的PBEKeySpec(password2.toCharArray(),salt,numIterations,keyLength*8))
.getEncoded();
//始终测试所有字节以防止定时攻击
整数位=0;
for(int i=0;i
这是安全哈希,而不是加密。