DEV Community

Cover image for What would you do if your encrypted credentials and the key got compromised?
Gokul G.K
Gokul G.K

Posted on

6 5 4 4 4

What would you do if your encrypted credentials and the key got compromised?

What will you do if your encrypted credentials and key got compromised?

This is a rhetorical question.

Securing API using API keys, tokens or password is common in any application. In the case of basic authentication generally, we try to store the credentials after encrypting them. Here let's see how we can use one-way hash functions like md5 or SHA-256 to achieve basic authentication.

The Idea

The idea is to have the credentials converted to hash strings using hash functions for the first time or during sign-up. During login, convert the user entered credentials to hash string and check for equality. Simple as that :D.

Image description

Here we aren't storing any encrypted passwords, so even if there is an attack on your application and data is compromised, your credentials are safe.

The Implementation

For a complete implementation of the same using java and spring boot (click here)

let me do a walkthrough :

so we have a minimal controller interface and implementation

@RestController
public interface LoginApi {

    @GetMapping("/user/login")
    @ResponseBody
    String userLogin();
}
Enter fullscreen mode Exit fullscreen mode
@Component
public class LoginApiImpl implements LoginApi{

    /**
     * User login string.
     *
     * @return the string
     */
    @Override
    public String userLogin() {
        return "Login Successful";
    }
}
Enter fullscreen mode Exit fullscreen mode

Then we have the filter implementation to verify authentication
Basic Authentication Filter Implementation

The service implementation is where we check the hashed string and given credential, for simplicity let's focus on password.

/**
 * The type Login service.
 */
@Service
public class LoginService {

    /**
     * The constant USER.
     */
    private static final String USER = "ADMIN";

    /**
     * The constant PASSWORD.
     * Actual value is : password
     */
    private static final String PASSWORD = "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8";

    /**
     * Check authentication boolean.
     *
     * @param user     the user
     * @param password the password
     * @return the boolean
     * @throws NoSuchAlgorithmException the no such algorithm exception
     */
    public boolean checkAuthentication(String user,String password) throws NoSuchAlgorithmException {
        String generatedHash = generateHash(password);
        if(PASSWORD.equals(generatedHash) && USER.equals(user))
            return true;
        return false;
    }

    /**
     * Generate hash string.
     *
     * @param password the password
     * @return the string
     * @throws NoSuchAlgorithmException the no such algorithm exception
     */
    public  String generateHash(String password) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hash =  md.digest(password.getBytes(StandardCharsets.UTF_8));
        BigInteger number = new BigInteger(1, hash);
        StringBuilder hexString = new StringBuilder(number.toString(16));
        while (hexString.length() < 64)
        {
            hexString.insert(0, '0');
        }
        return hexString.toString();
    }
}

Enter fullscreen mode Exit fullscreen mode

finally, let's run the code and hit the API {in this example username is: ADMIN and password is: password}

Here is the curl for the above API: curl --location --request GET 'http://localhost:8443/service/api/v1/user/login' \
--header 'Authorization: Basic QURNSU46cGFzc3dvcmQ='

Image description

That's all for now, Hope this is useful.
Share your thoughts in the comment section.

Image of AssemblyAI tool

Transforming Interviews into Publishable Stories with AssemblyAI

Insightview is a modern web application that streamlines the interview workflow for journalists. By leveraging AssemblyAI's LeMUR and Universal-2 technology, it transforms raw interview recordings into structured, actionable content, dramatically reducing the time from recording to publication.

Key Features:
🎥 Audio/video file upload with real-time preview
🗣️ Advanced transcription with speaker identification
⭐ Automatic highlight extraction of key moments
✍️ AI-powered article draft generation
📤 Export interview's subtitles in VTT format

Read full post

Top comments (2)

Collapse
 
blogger profile image
Coder

This is a better approach for basic auth.

Collapse
 
gokul_gk profile image
Gokul G.K

:D

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay