Shahril
Shahril

Reputation: 135

How to encrypt admin password?

In my java web app, admin account will create user account, where the password will be encrypted, using StandardPasswordEncoder class, that's easy. But how to encrypt the admin password, which i already stored in MySQL database?

Upvotes: 2

Views: 1472

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60016

how to encrypt the admin password, which i already stored in mysql database?

You can edit your password :

UPDATE table_name SET pass = MD5(pass);
-- --------------------------^^^-------
-- This can be any Standard encryption algorithm, you can check the link above

You can take a look about Encryption and Compression Functions

how if i only want to encrypt only the admin password? the other users password will be encrypted by admin in java controller class.

You can mark your password like a master admin for example you can add a column in your table that make difference between the admin and the ordinary users, consider you have a big enterprise in this case one admin account is not enough, you need many admin accounts, and in base of this column you can encrypt the admin account with an algorithm and the others with another algorithm.


Encrypt password using SHA-256

I managed to encrypt the admin password, but i can't log in to my web app coz the StandardPasswordEncoder class in the web app is using SHA-256 hashing algorithm

SHA-256 != MD5, this is clear so you have to use the same algothm in the both side code and database, in your case you are using SHA-256 i assume you are using a function like this :

CODE

public static String sha256(String base) {
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(base.getBytes("UTF-8"));
        StringBuilder hexString = new StringBuilder();

        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        return hexString.toString();
    } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
}

This will encrypt admin like this :

admin = 8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918

DATABASE

So in your database you have to encrypt your password like this :

SELECT SHA2('admin', 256);

The update query should look like this :

UPDATE table_name SET pass = SHA2(pass, 256) WHERE admin_master = true;
-- -------------Field to check if it is admin or not ---^

So when you try to log in you have to check if it is admin or not, if admin encrypt your password with SHA-256 and check if the user exist or not, else if the user is ordanary user, check with your previouse algorithm.

Hope this can give you an idea.

Upvotes: 2

Related Questions