I get two different values when converting a String to SHA1

1

I have the following code with which I am trying to encrypt passwords with SHA1. I have used code adapted from two different sources but both bring different results.

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;

public class Encriptacion 
{

    public static void main(String[] args) throws UnsupportedEncodingException {

        String password = "Lucas";

        try 
        {
            //da39a3ee5e6b4b0d3255bfef95601890afd80709
            MessageDigest md = MessageDigest.getInstance("SHA1");
            md.update(password.getBytes(), 0 , password.length());
            System.out.println(new BigInteger(1, md.digest()).toString(16));

            //CBEDE02E8C227684972AB1467409D98C0D0D5A5D
            MessageDigest msdDigest = MessageDigest.getInstance("SHA1");
            msdDigest.update(password.getBytes("UTF-8"), 0, password.length());
            password = DatatypeConverter.printHexBinary(msdDigest.digest());
            System.out.println(password);

        } 
        catch (NoSuchAlgorithmException ex) 
        {
            System.out.println("ERROR : ");
            ex.printStackTrace(System.out);
        }

    }

}

I do not know what is the reason why it brings me different results or what is the correct way to encrypt a password.

    
asked by Lucas. D 13.09.2017 в 19:48
source

1 answer

3

Both are correct and valid methods:

I)

    MessageDigest md = MessageDigest.getInstance("SHA1");
    md.update(password.getBytes(), 0 , password.length());
    System.out.println(new BigInteger(1, md.digest()).toString(16));

II)

    MessageDigest msdDigest = MessageDigest.getInstance("SHA1");
    msdDigest.update(password.getBytes("UTF-8"), 0, password.length());
    password = DatatypeConverter.printHexBinary(msdDigest.digest());
    System.out.println(password);

You can use both methods, both are correct, in the case of your question, if they are in the same method only ensures that when calling each one you must initialize your variable:

password = "Lucas";

in this way you will get the desired result.

As for the result% co_of% that you are getting, the reason is that the value of da39a3ee5e6b4b0d3255bfef95601890afd80709 is an empty String "".

    
answered by 13.09.2017 / 20:08
source