Skip to content

Commit

Permalink
refactor: 비밀번호 암호화 로직 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
khabh committed Aug 21, 2024
1 parent 8398825 commit 8a9f388
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ public boolean isTokenMismatch(String token) {
}

public boolean isPasswordMismatch(String rawPassword) {
Password password = new Password(rawPassword);
return !this.password.equals(password);
return !password.matches(rawPassword);
}
}
39 changes: 17 additions & 22 deletions server/src/main/java/server/haengdong/domain/event/Password.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.AccessLevel;
Expand All @@ -21,41 +20,37 @@ public class Password {
public static final int PASSWORD_LENGTH = 4;
private static final Pattern PASSWORD_PATTERN = Pattern.compile(String.format("^\\d{%d}$", PASSWORD_LENGTH));
private static final String HASH_ALGORITHM = "SHA-256";
private static final MessageDigest DIGEST;

private String value;

public Password(String password) {
validatePassword(password);
static {
try {
MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
byte[] hashedPassword = digest.digest(password.getBytes());
this.value = Base64.getEncoder().encodeToString(hashedPassword);
DIGEST = MessageDigest.getInstance(HASH_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("해시 알고리즘이 존재하지 않습니다.");
}
}

private String value;

public Password(String password) {
validatePassword(password);
this.value = encode(password);
}

private void validatePassword(String password) {
Matcher matcher = PASSWORD_PATTERN.matcher(password);
if (!matcher.matches()) {
throw new HaengdongException(HaengdongErrorCode.EVENT_PASSWORD_FORMAT_INVALID, "비밀번호는 4자리 숫자만 가능합니다.");
throw new HaengdongException(HaengdongErrorCode.EVENT_PASSWORD_FORMAT_INVALID);
}
}

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Password password = (Password) o;
return Objects.equals(this.value, password.value);
private String encode(String rawPassword) {
byte[] hashedPassword = DIGEST.digest(rawPassword.getBytes());
return Base64.getEncoder().encodeToString(hashedPassword);
}

@Override
public int hashCode() {
return Objects.hash(value);
public boolean matches(String rawPassword) {
String hashedPassword = encode(rawPassword);
return value.equals(hashedPassword);
}
}

0 comments on commit 8a9f388

Please sign in to comment.