0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Java] Spring Bootで文字列を暗号化する方法

Posted at

はじめに

パスワードを保存するとき、そのままDBに保存することはセキュリティ観点から望ましくない。よって文字列を暗号化して保存したら、もしDBに不正アクセスされても2次被害を防ぐことができる。
Spring Bootで暗号化する方法をまとめる。

Code

build.gradle
  implementation 'org.springframework.security:spring-security-crypto:5.7.1'
CommonConfig
@Configuration
public class CommonConfig {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}
AccountService.java
@Service
public class AccountService {

    @Autowired
    PasswordEncoder passwordEncoder;

    // 暗号化
    public String createEndocedPwd(String pwd) {
        String encodedPwd = passwordEncoder.encode(pwd);
        return encodedPwd;
    }

    // 暗号化されたあとのpw同士を比較する
    public boolean pwdMatch(String newPwd, String originPwd) {
        if (passwordEncoder.matches(newPwd, originPwd)) {
            return true;
        }
        return false;
    }
}

結果
1234 -> {bcrypt}$2a$10$TawJl5916Xs6/LnwWjPdXOdwLwsQqMWv38XDLELNpP.W.RL5zV2sK

暗号化され同じ文字列でも毎回異なる暗号を生成し、単方向暗号化であるため、暗号から元の文字列を推測することはできない。

終わりに

これで安心してDBにパスワードを保存できる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?