Implementing Password Encryption for User Authentication
User authentication systems require password protection mechanisms. When handling password data from client applications, encryption is essential before storage. MD5 hashing is commonly employed for this purpose. The verification process involves comparing the MD5 hash of the submitted password with the stored hash in the database.
Password hashing implementation:
String hashedPassword = DigestUtils.md5DigestAsHex(passwordInput.getBytes());
Controller layer authentication endpoint:
@PostMapping("/authenticate")
@ApiOperation("User authentication")
public ResponseResult<UserAuthVO> authenticate(@RequestBody UserAuthDTO authRequest) {
log.info("Authentication attempt: {}", authRequest);
User user = userService.authenticate(authRequest);
Map<String, Object> tokenClaims = new HashMap<>();
tokenClaims.put(JwtConstants.USER_ID, user.getId());
String authToken = JwtGenerator.generateToken(
jwtConfig.getSecretKey(),
jwtConfig.getTokenValidity(),
tokenClaims);
UserAuthVO authResponse = UserAuthVO.builder()
.id(user.getId())
.loginName(user.getLoginName())
.displayName(user.getDisplayName())
.authToken(authToken)
.build();
return ResponseResult.success(authResponse);
}
Service layer authentication logic:
public User authenticate(UserAuthDTO authData) {
String loginName = authData.getLoginName();
String passwordInput = authData.getPassword();
User userRecord = userRepository.findByLoginName(loginName);
if (userRecord == null) {
throw new UserNotFoundException(ErrorMessages.USER_NOT_FOUND);
}
String inputHash = DigestUtils.md5DigestAsHex(passwordInput.getBytes());
if (!inputHash.equals(userRecord.getPasswordHash())) {
throw new InvalidPasswordException(ErrorMessages.INVALID_CREDENTIALS);
}
if (userRecord.getStatus() == UserStatus.INACTIVE) {
throw new AccountDisabledException(ErrorMessages.ACCOUNT_DISABLED);
}
return userRecord;
}
Data access layer implemantation:
@Select("SELECT * FROM users WHERE login_name = #{loginName}")
User findByLoginName(String loginName);
JWT token generaiton utility:
public class JwtGenerator {
public static String generateToken(String secret, long validityMillis, Map<String, Object> claims) {
SignatureAlgorithm algorithm = SignatureAlgorithm.HS256;
long expirationTime = System.currentTimeMillis() + validityMillis;
Date expiryDate = new Date(expirationTime);
JwtBuilder tokenBuilder = Jwts.builder()
.setClaims(claims)
.signWith(algorithm, secret.getBytes(StandardCharsets.UTF_8))
.setExpiration(expiryDate);
return tokenBuilder.compact();
}
public static Claims decodeToken(String secret, String token) {
return Jwts.parser()
.setSigningKey(secret.getBytes(StandardCharsets.UTF_8))
.parseClaimsJws(token)
.getBody();
}
}