Search code examples
javaencryptionsha1

how to compare sha1 encripted password in Java?


Let say i have encripted SHA1 password like this

String pass = "f6ce584e7b4ff5253eed4a2ea2b44247";

and i want make condition like this :

 if (pass.equals("userinput")){
        System.out.println("success");
    }

please someone help me to make proper condition / function to compare those both value between user input and encripted password. Your help will be highly appreciated. thanks


Solution

  • SHA1 is a hash algorithm, which means that it is one-way. You can't get the original message after hashing it. Unlike encryption which is two-way (allows encryption and decryption).

    This means that if you want to compare a hash, you don't try to get the original message. Instead, you hash the message-to-be-compared as well, then you perform the match:

    So if the hashed pw is stored as:

    String pass = "f6ce584e7b4ff5253eed4a2ea2b44247";
    

    To match the subsequent input of the password, you do:

    //check if hashed userInput is also "f6ce584e7b4ff5253eed4a2ea2b44247"
    if(pass.equals(sha1(userInput))){          
        //do whatever
    }
    

    To implement a sha1() hash function, refer to: Java String to SHA1