I have the following code with which I am testing how to encrypt passwords with SHA1. I have used adapted code from two different sources but both bring me 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.
Both are correct and valid methods:
YO)
II)
You can use both methods, both are correct, in the case of your question, if they are in the same method it only ensures that when calling each one you must initialize your variable:
this way you will get the desired result.
As for the result
da39a3ee5e6b4b0d3255bfef95601890afd80709
you're getting, the reason is that the value ofpassword
is an empty String "".