What would you do if your encrypted credentials and the key got compromised?
Tags: api, security, tutorial, blog
Published: 2022-07-11 16:50:09

> 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1yn6orinkrjegxj4wj6e.png)

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](https://github.com/GKcodebase/Tutorials-blogs-workshop/tree/master/Blogs/Security/BasicAuthentication))

let me do a walkthrough :

so we have a minimal controller interface and implementation

```
@RestController
public interface LoginApi {

    @GetMapping("/user/login")
    @ResponseBody
    String userLogin();
}
```

```
@Component
public class LoginApiImpl implements LoginApi{

    /**
     * User login string.
     *
     * @return the string
     */
    @Override
    public String userLogin() {
        return "Login Successful";
    }
}
```
Then we have the filter implementation to verify authentication
[Basic Authentication Filter Implementation](https://github.com/GKcodebase/Tutorials-blogs-workshop/blob/master/Blogs/Security/BasicAuthentication/src/main/java/com/basicauth/infrastructure/filter/BasicAuthFilter.java)

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

```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0wnmmdm3wyj79k7zdowb.png)


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