Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Password Encryption for User Authentication

Tech 1

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();
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.